最近做的java项目有涉及到生成Poi Excel的模块,特此记录。
Version: java 1.8 Editor: IntelliJ
//生成xlsx,所以使用XSSF
//创建sheet
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(sheetName);
//设置字体、大小
Font font = wb.createFont();
font.setFontHeightInPoints(FONT_SIZE);
font.setFontName(FONT_NAME);
CellStyle style = wb.createCellStyle();
style.setFont(font);
//设置居中
style.setAlignment(HorizontalAlignment.CENTER);
//合并单元格
CellRangeAddress title = new CellRangeAddress(0, 0, 0, 7);
sheet.addMergedRegion(title);
//创建行、格
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(0);
//Excel API默认每列宽度相等
sheet.setColumnWidth(0, 600); //设置第0列 宽度为600
sheet.autoSizeColumn(0); //让第0列 根据内容自适应宽度
//输出 response为ServletResponse类
try {
wb.write(response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
} finally {
wb.close();
}