java poi 模板导出 套用表格格式

模板文件格式如下

 生成数据后样式如下

 

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     }
复制代码

 

posted on   天军  阅读(12)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示