利用poi 生成多個excel sheet
阿新 • • 發佈:2019-02-12
// 建立sheet @SuppressWarnings("unchecked") public void createExcelSheet(List list, String fileRealPath) throws Exception { HSSFWorkbook workBook = new HSSFWorkbook(); int page = 3; if(page > list.size() || list.size() <100){ page = 1; } for(int m=0;m<page;m++){ HSSFSheet sheet = workBook.createSheet(); workBook.setSheetName(m, "猜猜"+String.valueOf(m)); HSSFHeader header = sheet.getHeader(); header.setCenter("sheet"); HSSFRow headerRow = sheet.createRow(0); HSSFCellStyle headstyle = workBook.createCellStyle(); HSSFFont headfont = workBook.createFont(); headfont.setColor(HSSFColor.BLACK.index); headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); headstyle.setFont(headfont); for (int i = 0; i < tableHeader.size(); i++) { HSSFCell headerCell = headerRow.createCell(i); headerCell.setCellStyle(headstyle); // 設定cell的值 headerCell.setCellValue(tableHeader.get(i)); headerCell.setCellStyle(headstyle); } int rowIndex = 1; for (int i = ((list.size()/page)*m); i < ((list.size()/page)*(m+1)); i++) { System.out.println("總數:"+((list.size()/page)*(m+1))+"--"+i); List<String> list2 = (List<String>) list.get(i); HSSFRow row = sheet.createRow(rowIndex); for (int q = 0; q < list2.size(); q++) { // 建立第i個單元格 HSSFCell cell = row.createCell(q); cell.setCellValue(list2.get(q).replace("未知", "")); sheet.setColumnWidth(q, (80 * 50)); } rowIndex++; } FileOutputStream fos = new FileOutputStream(fileRealPath); sheet.setGridsPrinted(true); HSSFFooter footer = sheet.getFooter(); footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages()); workBook.write(fos); fos.close(); } }