说明:由于公司项目需求,需要将数据导出成Excel表格,并且可选择导出项,选择合计项,可下载。项目使用的Spring+Mybatis+SpringMVC框架,利用Apache POI导出Excel。因为需要导出的表格比较多,当然需要一个通用的工具类,思路是通过查找数据库注释当作表头,减少工作量。POI具体使用请自行百度。
流程
导出按钮触发查找数据库表controller并传递过去表名→查出来后展现在通用显示导出export_select.jsp→选择导出项与合计项后调用相应controller查找数据并调用ExportExcelUtil.java导出excel工具类ExportExcelUtil.java
package com.rixin.common.util;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Iterator;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Font;
/**
* 基于POI的javaee导出Excel工具类
*
* @author wjmisaboy@gmail.com
* @see POI
*/
public class ExportExcelUtil {
/**
*
* @param response
* 请求
* @param fileName
* 文件名 如:"学生表"
* @param excelHeaderArray
* excel表头数组,存放"姓名#name"格式字符串,"姓名"为excel标题行, "name"为对象字段名
* @param dataList
* 数据集合,需与表头数组中的字段名一致,并且符合javabean规范
* @param total
* 需要合计项字符串,","分割
* @return 返回一个HSSFWorkbook
* @throws Exception
*/
public static <T> HSSFWorkbook export(HttpServletResponse response, String fileName, String excelHeader,Collection<T> dataList, String total) throws Exception {
String[] excelHeaderArray = null;//表头数组
String[] totalArray = null;//合计项数组
if (excelHeader != null) {
excelHeaderArray = excelHeader.split(",");
} else {
return null;
}
if (total != null) {
totalArray = total.split(",");
}
// 设置请求
response.setContentType("application/application/vnd.ms-excel");
response.setHeader("Content-disposition",
"attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
// 创建一个Workbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 设置标题样式
HSSFCellStyle titleStyle = wb.createCellStyle();
// 设置单元格边框样式
titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框 细边线
titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 下边框 细边线
titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框 细边线
titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框 细边线
// 设置单元格对齐方式
titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中
titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中
// 设置字体样式
Font titleFont = wb.createFont();
titleFont.setFontHeightInPoints((short) 15); // 字体高度
titleFont.setFontName("黑体"); // 字体样式
titleStyle.setFont(titleFont);
// 在Workbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(fileName);
// 标题数组
String[] titleArray = new String[excelHeaderArray.length];
// 字段名数组
String[] fieldArray = new String[excelHeaderArray.length];
for (int i = 0; i < excelHeaderArray.length; i++) {
String[] tempArray = excelHeaderArray[i].split("#");// 临时数组 分割#
titleArray[i] = tempArray[0];
fieldArray[i] = tempArray[1];
}
// 在sheet中添加标题行
HSSFRow row = sheet.createRow((int) 0);// 行数从0开始
HSSFCell sequenceCell = row.createCell(0);// cell列 从0开始 第一列添加序号
sequenceCell.setCellValue("序号");
sequenceCell.setCellStyle(titleStyle);
sheet.autoSizeColumn(0);// 自动设置宽度
// 为标题行赋值
for (int i = 0; i < titleArray.length; i++) {
HSSFCell titleCell = row.createCell(i + 1);// 0号位被序号占用,所以需+1
titleCell.setCellValue(titleArray[i]);
titleCell.setCellStyle(titleStyle);
sheet.autoSizeColumn(i + 1);// 0号位被序号占用,所以需+1
}
// 数据样式 因为标题和数据样式不同 需要分开设置 不然会覆盖
HSSFCellStyle dataStyle = wb.createCellStyle();
// 设置数据边框
dataStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
dataStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
dataStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
dataStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
// 设置居中样式
dataStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中
dataStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中
// 设置数据字体
Font dataFont = wb.createFont();
dataFont.setFontHeightInPoints((short) 12); // 字体高度
dataFont.setFontName("宋体"); // 字体
dataStyle.setFont(dataFont);
// 遍历集合数据,产生数据行
Iterator<T> it = dataList.iterator();
int index = 0;
while (it.hasNext()) {
index++;// 0号位被占用 所以+1
row = sheet.createRow(index);
// 为序号赋值
HSSFCell sequenceCellValue = row.createCell(0);// 序号值永远是第0列
sequenceCellValue.setCellValue(index);
sequenceCellValue.setCellStyle(dataStyle);
sheet.autoSizeColumn(0);
T t = (T) it.next();
// 利用反射,根据传过来的字段名数组,动态调用对应的getXxx()方法得到属性值
for (int i = 0; i < fieldArray.length; i++) {
HSSFCell dataCell = row.createCell(i + 1);
dataCell.setCellStyle(dataStyle);
String fieldName = fieldArray[i];
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);// 取得对应getXxx()方法
Class<? extends Object> tCls = t.getClass();// 泛型为Object以及所有Object的子类
Method getMethod = tCls.getMethod(getMethodName, new Class[] {});// 通过方法名得到对应的方法
Object value = getMethod.invoke(t, new Object[] {});// 动态调用方,得到属性值
if (value != null) {
dataCell.setCellValue(value.toString());// 为当前列赋值
}
sheet.autoSizeColumn(i + 1);
}
}
// 合计项
if (totalArray != null) {
row = sheet.createRow(index + 1);
HSSFCell totalCell = row.createCell(0);// 序号值永远是第0列
totalCell.setCellValue("合计");
totalCell.setCellStyle(titleStyle);
sheet.autoSizeColumn(0);
for (int i = 0; i < fieldArray.length; i++) {
double sum = 0;
for (int j = 0; j < totalArray.length; j++) {
Iterator<T> iterator = dataList.iterator();
if (fieldArray[i].equals(totalArray[j])) {
String fieldName = fieldArray[i];
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);// 取得对应getXxx()方法
while (iterator.hasNext()) {
T t = (T) iterator.next();
Class<? extends Object> tCls = t.getClass();// 泛型为Object以及所有Object的子类
Method getMethod = tCls.getMethod(getMethodName, new Class[] {});// 通过方法名得到对应的方法
Object value = getMethod.invoke(t, new Object[] {});// 动态调用方,得到属性值
if (value != null && !"".equals(value)) {
sum += Double.parseDouble(value.toString());
}
}
break;
}
}
HSSFCell totalCellValue = row.createCell(i + 1);
totalCellValue.setCellStyle(titleStyle);
String val = "";
if (sum != 0) {
val = RxUtil.getNumber_ROUND_HALF_UP(String.valueOf(sum), 2);
}
totalCellValue.setCellValue(val);// 为当前列赋值
sheet.autoSizeColumn(i + 1);
}
}
OutputStream outputStream = response.getOutputStream();// 打开流
wb.write(outputStream);// HSSFWorkbook写入流
wb.close();// HSSFWorkbook关闭
outputStream.flush();// 刷新流
outputStream.close();// 关闭流
return wb;
}
// XSSFCellStyle.ALIGN_CENTER 居中对齐
// XSSFCellStyle.ALIGN_LEFT 左对齐
// XSSFCellStyle.ALIGN_RIGHT 右对齐
// XSSFCellStyle.VERTICAL_TOP 上对齐
// XSSFCellStyle.VERTICAL_CENTER 中对齐
// XSSFCellStyle.VERTICAL_BOTTOM 下对齐
// CellStyle.BORDER_DOUBLE 双边线
// CellStyle.BORDER_THIN 细边线
// CellStyle.BORDER_MEDIUM 中等边线
// CellStyle.BORDER_DASHED 虚线边线
// CellStyle.BORDER_HAIR 小圆点虚线边线
// CellStyle.BORDER_THICK 粗边线
}
- SQL查询数据库注释
SELECT
COLUMN_NAME field,
column_comment note
FROM
INFORMATION_SCHEMA. COLUMNS
WHERE
table_name = #{tableName}
AND
table_schema = 'boss'
注:COLUMN_NAME为字段名,需要和javabean保持一致,column_comment为注释。注释用”#”分割,有”#”说明可提供导出选择,”#”前面为excel表头名字,后面为注释,可不写。如需合计,在最后加上”,”。
有”#”的会显示在可选择导出项,有”,”的会显示在可选择合计项。
- TableInfoServiceImpl.java,用来查询数据库表的字段名与注释
package com.rixin.common.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.rixin.common.dao.ITableInfoDao;
import com.rixin.common.model.TableInfo;
@Service("TableInfoServiceImpl")
public class TableInfoServiceImpl implements ITableInfoService {
@Resource
private ITableInfoDao tableInfoDao;
@Override
public Map<String, Object> geTableInfoList(String tableName) {
Map<String, Object> result = new HashMap<String, Object>();
List<TableInfo> exportsList = tableInfoDao.getTableInfo(tableName);// 需要导出列表
List<TableInfo> totalsList = new ArrayList<TableInfo>();// 需要合计列表
Iterator<TableInfo> it = exportsList.iterator();// 迭代
while (it.hasNext()) {
TableInfo tableInfo = (TableInfo) it.next();
String note = tableInfo.getNote();// 注释
int index = note.indexOf("#");// '#'位置
// '#'存在,需要导出
if (index > 0) {
tableInfo.setNote(note.substring(0, index));//截取注释
int totalIndex = note.indexOf(",");
// ','存在,需要合计
if (totalIndex > 0) {
totalsList.add(tableInfo);// 添加到合计列表
}
} else {
it.remove();// 不需要导出,移除
}
}
result.put("exportsList", exportsList);
result.put("totalsList", totalsList);
return result;
}
}
- 需要导出的表格只需要写个controller即可
/**
* 导出Excel
*
* @return
* @throws IOException
*/
@RequestMapping("/exportExpenses.do")
public void exportExpenses(String export, String total, HttpServletResponse response, HttpSession session) {
Expenses expenses = new Expenses();
User sessionUser = (User) session.getAttribute("sessionUser");
// 查找数据
expenses.setCurrentUserId(sessionUser.getId());
expenses.setCurrentUserName(sessionUser.getUsername());
expenses.setCurrentUserDeptId(sessionUser.getDeptId());
expenses.setCurrentUserDeptName(sessionUser.getDeptName());
expenses.setCurrentUserDeptWholeId(sessionUser.getDeptWholeId());
List<Expenses> expensesList = expensesService.getExpensesList(expenses);
try {
ExportExcelUtil.export(response, "项目费用支出登记表", export, expensesList, total);
} catch (Exception e) {
e.printStackTrace();
}
}
- JSP需调用
<button class="am-btn am-btn-primary am-btn-sm"
<c:if test="${empty expensesList}">disabled="disabled"</c:if>
onclick="window.open('${basePath}tableInfo/getTableInfo.do?tableName=expenses')">
<span class="am-icon-bar-chart"></span> 导出
</button>
- 通用显示导出export_select.jsp
<div class="am-container" style="background-color: #FFFFFF">
<div data-am-widget="titlebar" class="am-titlebar am-titlebar-default">
<h2 class="am-titlebar-title ">选择导出项</h2>
<nav class="am-titlebar-nav"></nav>
</div>
<form class="am-form" method="post"
action="${basePath}${address}?state=${param.state}">
<div class="am-g">
<c:forEach items="${exportsList }" var="til">
<div style="margin-top: 5px;" class="am-u-sm-2">
<label class="am-checkbox"> <input type="checkbox"
value="${til.note }#${til.field }" name="export" data-am-ucheck
checked>${til.note }
</label>
</div>
</c:forEach>
<div align="center" class="am-u-sm-12 am-u-md-12"
style="margin-top: 0px; margin-bottom: 0px;"></div>
</div>
<div data-am-widget="titlebar"
class="am-titlebar am-titlebar-default">
<h2 class="am-titlebar-title ">选择合计项</h2>
<nav class="am-titlebar-nav"></nav>
</div>
<c:forEach items="${totalsList }" var="tl">
<div style="margin-top: 5px;" class="am-u-sm-2">
<label class="am-checkbox"> <input type="checkbox"
value="${tl.field }" name="total" data-am-ucheck checked>${tl.note }
</label>
</div>
</c:forEach>
<c:if test="${empty totalsList}">
<div style="margin-top: 15px;" class="am-u-sm-12" align="center">
<p>暂无可选择合计项!</p>
</div>
</c:if>
<div align="center" class="am-u-sm-12 am-u-md-12"
style="margin-top: 20px; margin-bottom: 20px;">
<c:if test="${viewstate ne 'read'}">
<button type="submit" id="subform" name="subform"
class="am-btn am-btn-primary" style="width: 100%">导出</button>
</c:if>
</div>
</form>
</div>
- 效果图
- 结束语
整个模块大概就是这样,需要导出哪个模块,只需要在页面上调用查找表信息的controller并传递过去表名,然后写一个controller来调用ExportExcelUtil.java即可。同时记得维护数据库注释。因为数据量多,所以想出这么一个方法,日后更改可导出项以及数据库字段名,只需维护数据库注释就可以了,这只是我个人的一点小思路,如果有更好的方法,欢迎讨论~