看代码之前先说一下此导出使用的开发框架,避免某些小可看了半天发现不能用
页面使用的是easyUI JSP
后台使用springboot
前台页面JS代码
function doExcel() {
let frozenColumns = $('#dg').datagrid('options').frozenColumns;
let columns = $('#dg').datagrid('options').columns;
let fieldAndTitle = [];
if (frozenColumns.length > 0 && columns.length > 0) {
for (let i = 0; i < columns.length; i++) {
for (let j = 0; j < frozenColumns.length; j++) {
if (i === j) {
fieldAndTitle.push(frozenColumns[j].concat(columns[i]));
}
if (i > j) {
fieldAndTitle.push(columns[i]);
}
break;
}
}
}
if(columns.length == 0 && frozenColumns.length > 0){
fieldAndTitle = frozenColumns;
}
if(frozenColumns.length == 0 && columns.length > 0){
fieldAndTitle = columns;
}
}
后台一个公用的方法,需要在接口里面调取这个方法,并把相关参数写上去就OK了
@RequestMapping(value = "/export")
public ResponseStatus download(HttpServletResponse response,MapBean mapBean){
ActionResult ar = ActionResult.New();
Map<String,Object> dataMap = paymentReportService.businessOperationList(mapBean,ar);
List<Map<String, Object>> dataList = (List<Map<String, Object>>) dataMap.get("rows");
Workbook workbook = getWorkBook(mapBean.getString("jspTitle"),dataList,mapBean.getString("fieldAndTitle"));
try {
String fileName =new String(mapBean.getString("jspTitle").toString().getBytes(), "iso-8859-1");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel;charset=utf8");
response.addHeader("Content-Disposition", "inline;filename=" + String.format("%s.xlsx",fileName));
ServletOutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return ar.toResponseStatus();
}
/**
* 导出共用方法
* @param sheetName 文件名
* @param dataList 数据
* @param fieldAndTitle 表头的列的json串
* @return
*/
private Workbook getWorkBook(String sheetName, List<Map<String, Object>> dataList,String fieldAndTitle){
Workbook workbook = new SXSSFWorkbook(100);
Sheet sheet = workbook.createSheet(sheetName);
//居中样式
CellStyle centerStyle = workbook.createCellStyle();
centerStyle.setAlignment(HorizontalAlignment.CENTER);
centerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//右对齐样式
CellStyle rightStyle = workbook.createCellStyle();
rightStyle.setAlignment(HorizontalAlignment.CENTER);
rightStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//日期样式
CellStyle dateStyle = workbook.createCellStyle();
dateStyle.setAlignment(HorizontalAlignment.CENTER);
dateStyle.setVerticalAlignment(VerticalAlignment.CENTER);
DataFormat format = workbook.createDataFormat();
dateStyle.setDataFormat(format.getFormat("yyyy-MM-dd"));
Row row = null;
Cell cell = null;
int rowIndex = 0;
int colIndex = 0;
int rowSpan;
int colSpan;
Map<Integer, String> indexMapper = New.map(); //列顺序索引
//标题
List<List<Map<String, Object>>> listList = JsonUtils.parseListListMap(fieldAndTitle);
List<List<Map<String, Object>>> finalListList = New.list();
for (List<Map<String, Object>> list : listList) {
List<Map<String, Object>> ll = New.list();
for (Map<String, Object> map : list) {
if (StringUtils.isNullOrEmpty(StringUtils.valueOf(map.get("title"))) || "操作".equals(StringUtils.valueOf(map.get("title")))) {
continue;
}
for (Map.Entry<String, Object> entry : map.entrySet()) {
if ("field".equals(entry.getKey())) {
map.put(entry.getKey(), entry.getValue());
break;
}
}
ll.add(map);
}
if (list.size() > 0) {
//需要保证表头的每个列表都要有数据,否则生成excel表格会出错
finalListList.add(ll);
}
}
if (finalListList.size() > 0) {
int lastRow, lastCol;
int column = 0;
for (Map<String,Object> header : finalListList.get(0)) {
column += ConvertUtils.toInt(header.get("colspan"),1);
}
boolean[][] blnRange = new boolean[finalListList.size()][column]; //二维表格矩陈,false表示可用,默认都可用
for (int i = 0; i < finalListList.size(); i++) {
row = sheet.createRow(rowIndex);
colIndex = 0; //如果是第一行,列索引从0开始
if (i > 0) {
//如果不是第一行,都要计算前面的单元格是否被占用
for (int k = 0; k < blnRange[0].length; k++) {
if (blnRange[i][k]) {
colIndex++; //如果被占用继续向后查
} else {
break; //否则,退出
}
}
}
for (Map<String, Object> map : finalListList.get(i)) {
rowSpan = ConvertUtils.toInt(StringUtils.valueOf(map.get("rowspan")),1);
colSpan = ConvertUtils.toInt(StringUtils.valueOf(map.get("colspan")),1);
if (rowSpan > 1 || colSpan > 1) {
//计算单元格结束的行与列
lastRow = rowSpan > 1 ? rowIndex + rowSpan - 1 : rowIndex;
lastCol = colSpan > 1 ? colIndex + colSpan - 1 : colIndex;
//生成合并的单元格
CellRangeAddress cra = new CellRangeAddress(rowIndex, lastRow, colIndex, lastCol);
sheet.addMergedRegion(cra);
cell = sheet.getRow(rowIndex).createCell(colIndex);
//cell = sheet.getRow(rowIndex).getCell(colIndex);
cell.setCellStyle(centerStyle);
cell.setCellValue(map.get("title").toString());
blnRange[rowIndex][colIndex] = true; //只改变当前单元格的状态
//改变合并的其他行的相应单元格状态
for (int k = rowIndex; k <= lastRow; k++) {
for (int j = colIndex; j <= lastCol; j++) {
blnRange[k][j] = true;
}
}
if (colSpan <= 1) {
indexMapper.put(colIndex, map.get("field").toString()); //添加列索引
}
colIndex = lastCol + 1;
} else {
cell = row.createCell(colIndex);
cell.setCellStyle(centerStyle);
cell.setCellValue(map.get("title").toString());
blnRange[rowIndex][colIndex] = true; //设置当前单元格已经被使用
indexMapper.put(colIndex, map.get("field").toString()); //添加列索引
colIndex++;
}
}
rowIndex++;
}
}
//数据
Object dataValue;
for (Map<String, Object> data : dataList) {
row = sheet.createRow(rowIndex++);
for (Map.Entry<Integer, String> entry : indexMapper.entrySet()) {
cell = row.createCell(entry.getKey());
dataValue = data.get(entry.getValue());
if (dataValue == null) {
cell.setCellValue("");
} else if (dataValue instanceof String) {
cell.setCellValue(String.valueOf(dataValue));
} else if (dataValue instanceof Integer ||
dataValue instanceof Short ||
dataValue instanceof Float ||
dataValue instanceof Double ||
dataValue instanceof BigDecimal) {
//让内容右对齐
cell.setCellStyle(rightStyle);
cell.setCellValue(Double.valueOf(String.valueOf(dataValue)));
} else if (dataValue instanceof Long) {
//长整形做字符串处理
cell.setCellValue(String.valueOf(dataValue));
} else if (dataValue instanceof Date) {
//日期类型
cell.setCellStyle(dateStyle);
cell.setCellValue((Date) dataValue);
} else if (dataValue instanceof Boolean) {
//日期类型
cell.setCellValue((Boolean) dataValue);
} else {
cell.setCellValue(String.valueOf(dataValue));
}
}
}
return workbook;
}