package com.mzl.flower.utils; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.util.CellRangeAddress; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ExcelExportUtil { //显示的导出表的标题 private String title; //导出表的列名 private String[] rowName ; private List headRows; private List dataList = new ArrayList<>(); private HttpServletResponse response; //默认日期格式 private String dateFormat = "yyyy-MM-dd"; public static class HeadRow{ int rowIndex; List columns; public HeadRow(int rowIndex, List columns){ this.columns = columns; this.rowIndex = rowIndex; } } public static class HeadColumn{ int columnIndex; int rowspan; int colspan; String name; public HeadColumn(int columnIndex, int rowspan, int colspan, String name){ this.columnIndex = columnIndex; this.rowspan = rowspan; this.colspan = colspan; this.name = name; } } public ExcelExportUtil(String title, List headRows, List dataList, HttpServletResponse response){ this.dataList = dataList; this.headRows = headRows; this.title = title; this.response = response; } public ExcelExportUtil(String title, List headRows, List dataList, HttpServletResponse response, String dateFormat){ this.dataList = dataList; this.headRows = headRows; this.title = title; this.response = response; this.dateFormat = dateFormat; } /** * 构造函数,传入要导出的数据 * @param title 标题 * @param rowName 列名 * @param dataList 数据集合 List * @param response http响应 */ public ExcelExportUtil(String title, String[] rowName, List dataList, HttpServletResponse response){ this.dataList = dataList; this.rowName = rowName; this.title = title; this.response = response; } /** * 构造函数,传入要导出的数据,带日期格式 * @param title 标题 * @param rowName 列名 * @param dataList 数据集合 List * @param response http响应 * @param dateFormat 日期格式 */ public ExcelExportUtil(String title, String[] rowName, List dataList, HttpServletResponse response, String dateFormat){ this.dataList = dataList; this.rowName = rowName; this.title = title; this.response = response; this.dateFormat = dateFormat; } private int prepareHeader(HSSFSheet sheet, HSSFCellStyle columnTopStyle){ int step = 0; if(headRows != null){ for(HeadRow row : headRows){ int firstRow = row.rowIndex; HSSFRow rowHeader = sheet.getRow(firstRow); if(rowHeader == null){ rowHeader = sheet.createRow(firstRow); } List columns = row.columns; int s = 1; for(HeadColumn c : columns){ int lastRow = firstRow + c.rowspan - 1; int firstCol = c.columnIndex; int lastCol = firstCol + c.colspan - 1; if(lastRow > firstRow || lastCol > firstCol) { for(int i = firstRow; i <= lastRow; i++){ for(int j = firstCol; j <= lastCol; j++){ HSSFRow rowHeader1 = sheet.getRow(i); if(rowHeader1 == null){ rowHeader1 = sheet.createRow(i); } HSSFCell cell = rowHeader1.getCell(j); if(cell == null){ cell = rowHeader1.createCell(j); } cell.setCellStyle(columnTopStyle); } } sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol)); } HSSFCell cell = rowHeader.getCell(firstCol); if(cell == null){ cell = rowHeader.createCell(firstCol); } cell.setCellStyle(columnTopStyle); cell.setCellType(CellType.STRING); HSSFRichTextString text = new HSSFRichTextString(c.name); cell.setCellValue(text); if(s < c.rowspan){ s = c.rowspan; } } step += s; } }else if(rowName != null){ // 产生表格标题行 HSSFRow rowTitle = sheet.createRow(0); HSSFCell cellTitle = rowTitle.createCell(0); sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1))); cellTitle.setCellStyle(columnTopStyle); cellTitle.setCellValue(title); // 定义所需列数 int columnNum = rowName.length; HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行) // 将列头设置到sheet的单元格中 for(int n = 0; n < columnNum; n++){ HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格 cellRowName.setCellType(CellType.STRING); //设置列头单元格的数据类型 HSSFRichTextString text = new HSSFRichTextString(rowName[n]); cellRowName.setCellValue(text); //设置列头单元格的值 cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式 } step = 3; } return step; } /* * 导出数据 * */ public void export() throws Exception{ try{ HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象 HSSFSheet sheet = workbook.createSheet(title); // 创建工作表 //sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】 HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象 HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象 int step = prepareHeader(sheet, columnTopStyle); //将查询出的数据设置到sheet对应的单元格中 if (null != dataList && dataList.size() > 0) { int cellNum = 0; for(int i = 0; i < dataList.size(); i++){ Object[] obj = dataList.get(i);//遍历每个对象 HSSFRow row = sheet.createRow(i + step);//创建所需的行数 for(int j = 0; j < obj.length; j++){ HSSFCell cell = row.createCell(j); //设置单元格的数据类型 //HSSFCell cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING); //设置单元格的数据类型 cell.setCellStyle(style); //设置单元格样式 cellNum = setCellValue(cell, obj[j], cellNum, row); cellNum++; } } } if(workbook !=null){ OutputStream out = null; try{ String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls"; String headStr = "attachment; filename=\"" + fileName + "\""; response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", headStr); response.addHeader("filename", URLEncoder.encode(fileName, "UTF-8")); out = response.getOutputStream(); workbook.write(out); out.flush(); } catch (IOException e){ } finally{ if (null != out){ out.close(); } } } }catch(Exception e){ e.printStackTrace(); } } private int setCellValue(HSSFCell cell, Object value, int cellNum, HSSFRow row){ String textValue = null; if (value instanceof Integer) { int intValue = (Integer) value; cell.setCellValue(intValue); } else if (value instanceof Float) { float fValue = (Float) value; cell.setCellValue(fValue); } else if (value instanceof Double) { double dValue = (Double) value; cell.setCellValue(dValue); } else if (value instanceof Long) { long longValue = (Long) value; cell.setCellValue(longValue); } else if (value instanceof Boolean) { boolean bValue = (Boolean) value; cell.setCellValue(bValue); } else if (value instanceof Date) { Date date = (Date) value; SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); textValue = sdf.format(date); } else if (value instanceof ZonedDateTime){ DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormat); textValue = dateTimeFormatter.format((ZonedDateTime) value); }else if (value instanceof String[]) { String[] strArr = (String[]) value; for (int j = 0; j < strArr.length; j++) { String str = strArr[j]; cell.setCellValue(str); if (j != strArr.length - 1) { cellNum++; cell = row.createCell(cellNum); } } } else if (value instanceof Double[]) { Double[] douArr = (Double[]) value; for (int j = 0; j < douArr.length; j++) { Double val = douArr[j]; // 值不为空则set Value if (val != null) { cell.setCellValue(val); } if (j != douArr.length - 1) { cellNum++; cell = row.createCell(cellNum); } } } else { // 其它数据类型都当作字符串简单处理 String empty = ""; textValue = value == null ? empty : value.toString(); } if (textValue != null) { HSSFRichTextString richString = new HSSFRichTextString(textValue); cell.setCellValue(richString); } return cellNum; } /* * 列头单元格样式 */ private HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) { // 设置字体 HSSFFont font = workbook.createFont(); //设置字体大小 font.setFontHeightInPoints((short)11); //字体加粗 font.setBold(true); //设置字体名字 font.setFontName("Courier New"); //设置样式; HSSFCellStyle style = workbook.createCellStyle(); //设置底边框; style.setBorderBottom(BorderStyle.THIN); //设置底边框颜色; style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex()); //设置左边框; style.setBorderLeft(BorderStyle.THIN); //设置左边框颜色; style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex()); //设置右边框; style.setBorderRight(BorderStyle.THIN); //设置右边框颜色; style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex()); //设置顶边框; style.setBorderTop(BorderStyle.THIN); //设置顶边框颜色; style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex()); //在样式用应用设置的字体; style.setFont(font); //设置自动换行; style.setWrapText(false); //设置水平对齐的样式为居中对齐; style.setAlignment(HorizontalAlignment.CENTER); //设置垂直对齐的样式为居中对齐; style.setVerticalAlignment(VerticalAlignment.CENTER); return style; } /* * 列数据信息单元格样式 */ private HSSFCellStyle getStyle(HSSFWorkbook workbook) { // 设置字体 HSSFFont font = workbook.createFont(); //设置字体大小 //font.setFontHeightInPoints((short)10); //字体加粗 //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //设置字体名字 font.setFontName("Courier New"); //设置样式; HSSFCellStyle style = workbook.createCellStyle(); //设置底边框; style.setBorderBottom(BorderStyle.THIN); //设置底边框颜色; style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex()); //设置左边框; style.setBorderLeft(BorderStyle.THIN); //设置左边框颜色; style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex()); //设置右边框; style.setBorderRight(BorderStyle.THIN); //设置右边框颜色; style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex()); //设置顶边框; style.setBorderTop(BorderStyle.THIN); //设置顶边框颜色; style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex()); //在样式用应用设置的字体; style.setFont(font); //设置自动换行; style.setWrapText(true); //设置水平对齐的样式为居中对齐; style.setAlignment(HorizontalAlignment.CENTER); //设置垂直对齐的样式为居中对齐; style.setVerticalAlignment(VerticalAlignment.CENTER); return style; } }