模板文件格式如下
生成数据后样式如下
poi3.17
excel2007已上 xlsx
直接上代码。拿走不谢!
1 public static XSSFWorkbook readTemplate(String filePath) throws IOException { 2 try (FileInputStream fis = new FileInputStream(filePath)) { 3 return new XSSFWorkbook(fis); 4 } 5 } 6 7 //套用表格样式 8 @SneakyThrows 9 public static void main(String[] args) { 10 11 // 创建一个新的工作簿,从现有的Excel模板 12 XSSFWorkbook workbook = readTemplate("D:\\test.xlsx"); 13 // XSSFWorkbook workbook = new XSSFWorkbook("D:\\test.xlsx"); 14 XSSFSheet sheet = workbook.getSheetAt(0); 15 16 // 创建数据格式对象 17 XSSFDataFormat format = workbook.createDataFormat(); 18 // 获取货币格式,这里以人民币符号为例 19 short formatFormat = format.getFormat("¥#,##0.00"); 20 21 for (int i = 0; i < 10; i++) { 22 // // 假设我们要在索引为1的位置插入一行 23 int rowIndex = i + 1; 24 // sheet.shiftRows(rowIndex, sheet.getLastRowNum(), 1); 25 Row newRow = sheet.createRow(rowIndex); // 创建新行 26 27 // 在新行中创建单元格并设置值 28 Cell cell0 = newRow.createCell(0); 29 cell0.setCellValue("aa" + rowIndex); 30 31 Cell cell1 = newRow.createCell(1); 32 cell1.setCellValue(rowIndex); 33 34 Cell cell2 = newRow.createCell(2); 35 cell2.setCellValue(rowIndex); 36 cell2.setCellStyle(workbook.createCellStyle()); // 创建新的单元格样式 37 cell2.getCellStyle().setDataFormat(formatFormat); // 应用货币格式 38 } 39 40 //修改套用表格格式的区域 41 List<XSSFTable> tables = sheet.getTables(); 42 XSSFTable xssfTable = tables.get(0); 43 //注意 区域 每次只能 横向或者纵向调整,不能 横纵向一块调整 例如(原A1:A10;只能A1:A5或者A1:C10。不能一次性调整到A1:C5) 44 // AreaReference areaReference = new AreaReference(new CellReference(0,0), new CellReference(10,2), SpreadsheetVersion.EXCEL2007); 45 AreaReference areaReference = new AreaReference("A1:C11", SpreadsheetVersion.EXCEL2007); 46 xssfTable.setCellReferences(areaReference); 47 48 // 写入到文件 49 try (FileOutputStream outputStream = new FileOutputStream("D:\\test1.xlsx")) { 50 workbook.write(outputStream); 51 } catch (IOException e) { 52 e.printStackTrace(); 53 } finally { 54 try { 55 workbook.close(); 56 } catch (IOException e) { 57 e.printStackTrace(); 58 } 59 } 60 }
标签:sheet,java,rowIndex,A1,poi,workbook,new,XSSFWorkbook,模板 From: https://www.cnblogs.com/h2285409/p/18664078