1.首先需要一个实体类
import lombok.Data;
@Data
public class PoiModel {
private String content;
private String oldContent;
private int rowIndex;
private int cellIndex;
}
2.导出表格工具类
package com.ccb.financial.common.utils;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import com.ccb.financial.model.PoiModel;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.google.common.collect.Lists;
public class ExportExcelByPoiUtil {
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
@SuppressWarnings("rawtypes")
public static String createExcel(HttpServletResponse response,String[] title,String titleHead ,int[] widthAttr,Map<String, List<Map<String, String>>> maps, int[] mergeIndex){
String now = sdf.format(new Date());
if (title.length==0){
return null;
}
Workbook workbook = new XSSFWorkbook();
Sheet sheet = null;
int n = 0;
for(Map.Entry<String, List<Map<String, String>>> entry : maps.entrySet()){
try {
sheet = workbook.createSheet();
workbook.setSheetName(n, entry.getKey());
workbook.setSelectedTab(0);
}catch (Exception e){
e.printStackTrace();
}
CellStyle cellStyle_head = style(0, workbook);
CellStyle cellStyle_export = style(3, workbook);
CellStyle cellStyle_title = style(1, workbook);
CellStyle cellStyle = style(2, workbook);
CellRangeAddress c1 = new CellRangeAddress(0, 0, 0, title.length-1);
sheet.addMergedRegion(c1);
CellRangeAddress c2 = new CellRangeAddress(1, 1, 0, title.length-1);
sheet.addMergedRegion(c2);
Row row0 = sheet.createRow(0);
Cell cell1 = row0.createCell(0);
cell1.setCellValue(entry.getKey());
cell1.setCellStyle(cellStyle_head);
setRegionStyle(sheet, c1, cellStyle_head);
for (int i = 0; i < widthAttr.length; i++) {
sheet.setColumnWidth((short) i, (short) widthAttr[i] * 200);
}
Row row1 = sheet.createRow(1);
Cell cell2 = row1.createCell(0);
cell2.setCellValue("导出时间:" + now);
cell2.setCellStyle(cellStyle_export);
setRegionStyle(sheet, c2, cellStyle_export);
Row row2 = sheet.createRow(2);
for(int i = 0; i<title.length; i++){
Cell cell_1 = row2.createCell(i, Cell.CELL_TYPE_STRING);
cell_1.setCellValue(title[i]);
cell_1.setCellStyle(cellStyle_title);
}
List<Map<String, String>> list