Java利用POI生成Excel(.xls和.xlsx)
更多请参考: http://poi.apache.org/spreadsheet/quick-guide.html
这里是生成Excel并加入一些样式的例子.
Maven依赖:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency>
核心代码:
private String getMuiltpleSheetContent(List<SheetVo> dataList) { ByteArrayOutputStream out = null; try { // create WritableWorkbook XSSFWorkbook workbook = new XSSFWorkbook(); XSSFCellStyle styleHeader = generateHeaderStyle(workbook); if (null != dataList) { List<String> columnNames = null; List<Map<String,Object>> rows = null; Map<String,Object> row = null; XSSFRow xssfRow = null; String titleActive = null; String datePattern = null; int offset = 0; // generate cell style. XSSFCellStyle evenAlignLeft = generateCellStyle4EvenAlignLeft(workbook); XSSFCellStyle evenAlignRight = generateCellStyle4EvenAlignRight(workbook); XSSFCellStyle oddAlignLeft = generateCellStyle4OddAlignLeft(workbook); XSSFCellStyle oddAlignRight = generateCellStyle4OddAlignRight(workbook); for (SheetVo sheetVo:dataList) { columnNames = sheetVo.getColumnNames(); rows = sheetVo.getRows(); titleActive = sheetVo.getTitleActive(); datePattern = sheetVo.getDatePattern(); // createSheet has to param,the first one is sheet name, the second is position XSSFSheet sheet = workbook.createSheet(sheetVo.getSheetName()); // generate cells for sheet int columnsSize = columnNames.size(); XSSFCell cell = null; // generate header row if (null != titleActive && "N".equals(titleActive)) { offset = 0; LOG.info("RDS INFO! Ignore titile for sheet: {}", sheetVo.getSheetName()); } else { offset = 1; xssfRow = sheet.createRow(0); for (int i = 0;i < columnsSize;i++) { // add cell to sheet cell = xssfRow.createCell(i); cell.setCellType(XSSFCell.CELL_TYPE_STRING); cell.setCellStyle(styleHeader); cell.setCellValue(columnNames.get(i)); } } // generate content rows Object cellValue = null; int rowSize = rows.size(); int rowIndex = 0; for (int i = 0;i < rowSize;i++) { rowIndex = i + offset; xssfRow = sheet.createRow(rowIndex); row = rows.get(i); for (int j = 0;j < columnsSize;j++) { cell = xssfRow.createCell(j); cellValue = row.get(columnNames.get(j)); cell.setCellType(XSSFCell.CELL_TYPE_STRING); setCellValue(cell, cellValue, datePattern); cell.setCellStyle(generateCellStyle(rowIndex, cellValue, evenAlignRight, evenAlignLeft, oddAlignRight, oddAlignLeft)); } } // set auto width for each column for (int i = 0;i < columnsSize;i++) { sheet.autoSizeColumn(i); } } } out = new ByteArrayOutputStream(); workbook.write(out); return RDSUtil.encodeToBase64String(out.toByteArray()); } catch (Exception e) { LOG.error("RDS ERROR!", e); return ""; } finally { try { if (null != out) { out.close(); } } catch (IOException e) { LOG.error("RDS ERROR!", e); } } } private void setCellValue(XSSFCell cell, Object cellValue, String datePattern) { if (null == cellValue) { return; } // Number is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short. if (cellValue instanceof Number) { cell.setCellValue(((Number) cellValue).doubleValue()); } else if (cellValue instanceof Date) { String cellValueString = null; Date date = (Date) cellValue; if (null != datePattern) { try { cellValueString = new SimpleDateFormat(datePattern).format(date); } catch (Exception e) { cellValueString = null; } } if (null == cellValueString) { cellValueString = RdsUtil.getOnlyDatetimeString(date); } cell.setCellValue(cellValueString); } else { cell.setCellValue(cellValue.toString()); } } private XSSFCellStyle generateHeaderStyle(XSSFWorkbook workbook) { XSSFCellStyle styleHeader = workbook.createCellStyle(); styleHeader.setAlignment(XSSFCellStyle.ALIGN_CENTER); styleHeader.setWrapText(false); styleHeader.setBorderColor(BorderSide.LEFT, new XSSFColor(Color.WHITE)); styleHeader.setBorderColor(BorderSide.BOTTOM, new XSSFColor(Color.WHITE)); styleHeader.setBorderColor(BorderSide.RIGHT, new XSSFColor(Color.WHITE)); styleHeader.setBorderColor(BorderSide.TOP, new XSSFColor(Color.WHITE)); styleHeader.setBorderLeft(BorderStyle.THIN); styleHeader.setBorderBottom(BorderStyle.THIN); styleHeader.setBorderRight(BorderStyle.THIN); styleHeader.setBorderTop(BorderStyle.THIN); XSSFFont fontHeader = (XSSFFont) workbook.createFont(); fontHeader.setFontName("ARIAL"); fontHeader.setBold(true); fontHeader.setFontHeightInPoints((short) 10); fontHeader.setColor(IndexedColors.WHITE.getIndex()); styleHeader.setFont(fontHeader); styleHeader.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); styleHeader.setFillForegroundColor(new XSSFColor(Color.decode("#33CCCC"))); // style.setFillBackgroundColor(IndexedColors.RED.getIndex()); // style.setFillBackgroundColor(new XSSFColor(java.awt.Color.GREEN)); return styleHeader; } private XSSFCellStyle generateCellStyle(int row, Object cellValue, XSSFCellStyle evenAlignRight, XSSFCellStyle evenAlignLeft, XSSFCellStyle oddAlignRight, XSSFCellStyle oddAlignLeft) { boolean isEven = (row % 2 == 0); boolean isAlighRight = false; if (cellValue instanceof Number || cellValue instanceof Date) { isAlighRight = true; } if (isEven && isAlighRight) { return evenAlignRight; } else if (isEven) { return evenAlignLeft; } else if (isAlighRight) { return oddAlignRight; } else { return oddAlignLeft; } } private XSSFCellStyle generateCellStyle4EvenAlignRight(XSSFWorkbook workbook) { XSSFCellStyle styleCell = generateCellDefaultStyle(workbook); styleCell.setFillForegroundColor(new XSSFColor(Color.decode("#CCFFCC")));// #F4FFFF styleCell.setAlignment(XSSFCellStyle.ALIGN_RIGHT); return styleCell; } private XSSFCellStyle generateCellStyle4EvenAlignLeft(XSSFWorkbook workbook) { XSSFCellStyle styleCell = generateCellDefaultStyle(workbook); styleCell.setFillForegroundColor(new XSSFColor(Color.decode("#CCFFCC"))); return styleCell; } private XSSFCellStyle generateCellStyle4OddAlignRight(XSSFWorkbook workbook) { XSSFCellStyle styleCell = generateCellDefaultStyle(workbook); styleCell.setAlignment(XSSFCellStyle.ALIGN_RIGHT); return styleCell; } private XSSFCellStyle generateCellStyle4OddAlignLeft(XSSFWorkbook workbook) { XSSFCellStyle styleCell = generateCellDefaultStyle(workbook); return styleCell; } private XSSFCellStyle generateCellDefaultStyle(XSSFWorkbook workbook) { XSSFCellStyle styleCell = workbook.createCellStyle(); styleCell.setWrapText(false); styleCell.setBorderColor(BorderSide.LEFT, new XSSFColor(Color.GRAY)); styleCell.setBorderColor(BorderSide.BOTTOM, new XSSFColor(Color.GRAY)); styleCell.setBorderColor(BorderSide.RIGHT, new XSSFColor(Color.GRAY)); styleCell.setBorderColor(BorderSide.TOP, new XSSFColor(Color.GRAY)); styleCell.setBorderLeft(BorderStyle.THIN); styleCell.setBorderBottom(BorderStyle.THIN); styleCell.setBorderRight(BorderStyle.THIN); styleCell.setBorderTop(BorderStyle.THIN); XSSFFont fontCell = workbook.createFont(); fontCell.setFontName("ARIAL"); fontCell.setFontHeightInPoints((short) 10); styleCell.setFont(fontCell); styleCell.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); return styleCell; }
Base64字节编码和解码:
public static String encodeToBase64String(byte[] bytes) { return Base64Utils.tob64(bytes); } public static byte[] decodeToBase64Byte(String str) { return Base64Utils.fromb64(str); }
引用实体Vo:
public class SheetVo implements Serializable { /** * */ private static final long serialVersionUID = -7307728417389899304L; private String sheetName; private String titleActive; private String datePattern; private List<String> columnNames; private List<Map<String,Object>> rows; public SheetVo() { } public SheetVo(List<String> columnNames, List<Map<String,Object>> rows) { this.columnNames = columnNames; this.rows = rows; } public String getSheetName() { return sheetName; } public void setSheetName(String sheetName) { this.sheetName = sheetName; } public String getTitleActive() { return titleActive; } public void setTitleActive(String titleActive) { this.titleActive = titleActive; } public List<String> getColumnNames() { return columnNames; } public void setColumnNames(List<String> columnNames) { this.columnNames = columnNames; } public List<Map<String,Object>> getRows() { return rows; } public void setRows(List<Map<String,Object>> rows) { this.rows = rows; } public String getDatePattern() { return datePattern; } public void setDatePattern(String datePattern) { this.datePattern = datePattern; } }
使用HSSFWorkbook并自定义填充颜色:
private String getMuiltpleSheetContent(List<SheetVo> dataList) { ByteArrayOutputStream out = null; try { // create WritableWorkbook HSSFWorkbook workbook = new HSSFWorkbook(); HSSFCellStyle styleHeader = generateHeaderStyle(workbook); if (null != dataList) { List<String> columnNames = null; List<Map<String,Object>> rows = null; Map<String,Object> row = null; HSSFRow xssfRow = null; String titleActive = null; String datePattern = null; int offset = 0; addCustomColor(workbook); // generate cell style. HSSFCellStyle evenAlignLeft = generateCellStyle4EvenAlignLeft(workbook); HSSFCellStyle evenAlignRight = generateCellStyle4EvenAlignRight(workbook); HSSFCellStyle oddAlignLeft = generateCellStyle4OddAlignLeft(workbook); HSSFCellStyle oddAlignRight = generateCellStyle4OddAlignRight(workbook); for (SheetVo sheetVo:dataList) { columnNames = sheetVo.getColumnNames(); rows = sheetVo.getRows(); titleActive = sheetVo.getTitleActive(); datePattern = sheetVo.getDatePattern(); // createSheet has to param,the first one is sheet name, the second is position HSSFSheet sheet = workbook.createSheet(sheetVo.getSheetName()); // generate cells for sheet int columnsSize = columnNames.size(); HSSFCell cell = null; // generate header row if (null != titleActive && "N".equals(titleActive)) { offset = 0; LOG.info("RDS INFO! Ignore titile for sheet: {}", sheetVo.getSheetName()); } else { offset = 1; xssfRow = sheet.createRow(0); for (int i = 0;i < columnsSize;i++) { // add cell to sheet cell = xssfRow.createCell(i); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setCellStyle(styleHeader); cell.setCellValue(columnNames.get(i)); } } // generate content rows Object cellValue = null; int rowSize = rows.size(); int rowIndex = 0; for (int i = 0;i < rowSize;i++) { rowIndex = i + offset; xssfRow = sheet.createRow(rowIndex); row = rows.get(i); for (int j = 0;j < columnsSize;j++) { cell = xssfRow.createCell(j); cellValue = row.get(columnNames.get(j)); cell.setCellType(HSSFCell.CELL_TYPE_STRING); setCellValue(cell, cellValue, datePattern); cell.setCellStyle(generateCellStyle(i + 1, cellValue, evenAlignRight, evenAlignLeft, oddAlignRight, oddAlignLeft)); } } // set auto width for each column for (int i = 0;i < columnsSize;i++) { sheet.autoSizeColumn(i); } } } out = new ByteArrayOutputStream(); workbook.write(out); return RDSUtil.encodeToBase64String(out.toByteArray()); } catch (Exception e) { LOG.error("RDS ERROR!", e); return ""; } finally { try { if (null != out) { out.close(); } } catch (IOException e) { LOG.error("RDS ERROR!", e); } } } private void setCellValue(HSSFCell cell, Object cellValue, String datePattern) { if (null == cellValue) { cell.setCellType(Cell.CELL_TYPE_BLANK); return; } // Number is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short. if (cellValue instanceof Number) { cell.setCellValue(((Number) cellValue).doubleValue()); } else if (cellValue instanceof Date) { String cellValueString = null; Date date = (Date) cellValue; if (null != datePattern) { try { cellValueString = new SimpleDateFormat(datePattern).format(date); } catch (Exception e) { cellValueString = null; } } if (null == cellValueString) { cellValueString = RdsUtil.getOnlyDatetimeString(date); } cell.setCellValue(cellValueString); } else { cell.setCellValue(cellValue.toString()); } } private void addCustomColor(HSSFWorkbook workbook) { HSSFPalette palette = workbook.getCustomPalette(); palette.setColorAtIndex(IndexedColors.PLUM.getIndex(), (byte) (223), (byte) (239), (byte) (255));// #DFEFFF Header background. palette.setColorAtIndex(IndexedColors.INDIGO.getIndex(), (byte) (216), (byte) (231), (byte) (231));// #D8E7E7 Content background. palette.setColorAtIndex(IndexedColors.GREY_80_PERCENT.getIndex(), (byte) (153), (byte) (204), (byte) (255));// #99CCFF Border. } private HSSFCellStyle generateHeaderStyle(HSSFWorkbook workbook) { HSSFCellStyle styleHeader = workbook.createCellStyle(); styleHeader.setAlignment(HSSFCellStyle.ALIGN_CENTER); styleHeader.setWrapText(false); styleHeader.setLeftBorderColor(IndexedColors.GREY_80_PERCENT.getIndex()); styleHeader.setBottomBorderColor(IndexedColors.GREY_80_PERCENT.getIndex()); styleHeader.setRightBorderColor(IndexedColors.GREY_80_PERCENT.getIndex()); styleHeader.setTopBorderColor(IndexedColors.GREY_80_PERCENT.getIndex()); styleHeader.setBorderLeft(CellStyle.BORDER_THIN); styleHeader.setBorderBottom(CellStyle.BORDER_THIN); styleHeader.setBorderRight(CellStyle.BORDER_THIN); styleHeader.setBorderTop(CellStyle.BORDER_THIN); HSSFFont fontHeader = (HSSFFont) workbook.createFont(); fontHeader.setFontName("ARIAL"); fontHeader.setBoldweight(Font.BOLDWEIGHT_BOLD); fontHeader.setFontHeightInPoints((short) 10); fontHeader.setColor(IndexedColors.BLACK.getIndex()); styleHeader.setFont(fontHeader); styleHeader.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); styleHeader.setFillForegroundColor(IndexedColors.PLUM.getIndex()); // styleHeader.setFillBackgroundColor(HSSFCellStyle.SOLID_FOREGROUND); // styleHeader.setFillBackgroundColor(new HSSFColor(Color.decode("#DFEFFF"))); return styleHeader; } private HSSFCellStyle generateCellStyle(int row, Object cellValue, HSSFCellStyle evenAlignRight, HSSFCellStyle evenAlignLeft, HSSFCellStyle oddAlignRight, HSSFCellStyle oddAlignLeft) { boolean isEven = (row % 2 == 0); boolean isAlighRight = false; if (cellValue instanceof Number || cellValue instanceof Date) { isAlighRight = true; } if (isEven && isAlighRight) { return evenAlignRight; } else if (isEven) { return evenAlignLeft; } else if (isAlighRight) { return oddAlignRight; } else { return oddAlignLeft; } } private HSSFCellStyle generateCellStyle4EvenAlignRight(HSSFWorkbook workbook) { HSSFCellStyle styleCell = generateCellDefaultStyle(workbook); styleCell.setFillForegroundColor(IndexedColors.INDIGO.getIndex()); styleCell.setAlignment(HSSFCellStyle.ALIGN_RIGHT); return styleCell; } private HSSFCellStyle generateCellStyle4EvenAlignLeft(HSSFWorkbook workbook) { HSSFCellStyle styleCell = generateCellDefaultStyle(workbook); styleCell.setFillForegroundColor(IndexedColors.INDIGO.getIndex()); return styleCell; } private HSSFCellStyle generateCellStyle4OddAlignRight(HSSFWorkbook workbook) { HSSFCellStyle styleCell = generateCellDefaultStyle(workbook); styleCell.setFillForegroundColor(HSSFColor.WHITE.index); styleCell.setAlignment(HSSFCellStyle.ALIGN_RIGHT); return styleCell; } private HSSFCellStyle generateCellStyle4OddAlignLeft(HSSFWorkbook workbook) { HSSFCellStyle styleCell = generateCellDefaultStyle(workbook); styleCell.setFillForegroundColor(HSSFColor.WHITE.index); return styleCell; } private HSSFCellStyle generateCellDefaultStyle(HSSFWorkbook workbook) { HSSFCellStyle styleCell = workbook.createCellStyle(); styleCell.setWrapText(false); styleCell.setLeftBorderColor(IndexedColors.GREY_80_PERCENT.getIndex()); styleCell.setBottomBorderColor(IndexedColors.GREY_80_PERCENT.getIndex()); styleCell.setRightBorderColor(IndexedColors.GREY_80_PERCENT.getIndex()); styleCell.setTopBorderColor(IndexedColors.GREY_80_PERCENT.getIndex()); styleCell.setBorderLeft(CellStyle.BORDER_THIN); styleCell.setBorderBottom(CellStyle.BORDER_THIN); styleCell.setBorderRight(CellStyle.BORDER_THIN); styleCell.setBorderTop(CellStyle.BORDER_THIN); HSSFFont fontCell = workbook.createFont(); fontCell.setFontName("ARIAL"); fontCell.setFontHeightInPoints((short) 10); styleCell.setFont(fontCell); styleCell.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); return styleCell; }