8

我找到了以下代码,可以从现有模板中创建一个带有格式的 Excel 工作表,并向其中添加数据并将其保存到一个新文件中

POIFSFileSystem fs = new POIFSFileSystem(
            new FileInputStream("template.xls"));
HSSFWorkbook wb = new  HSSFWorkbook(fs, true);
Will load an xls, preserving its structure (macros included). You can then modify it,

HSSFSheet sheet1 = wb.getSheet("Data"); ...

然后保存它。

FileOutputStream fileOut = new FileOutputStream("new.xls"); 
wb.write(fileOut);
fileOut.close();

这绝对没问题。但我的问题是我现在正在处理新版本的 excel。所以我需要开发一个类似的代码来处理新版本的模板。有人可以建议我该怎么做吗?我尝试将 HSSWorkbook 更改为 XSSFWorkbook。但是 XSSFWorkbook 没有让我传递布尔值的构造函数。还。当我尝试它时,它会复制数据,但带有数据的行不保留模板所具有的列的格式。

4

2 回答 2

9

This should work fine (though it's always best to use the latest version of POI for all the bug fixes):

Workbook wb = new XSSFWorkbook( OPCPackage.open("template.xlsx") );
Sheet sheet = wb.getSheetAt(0);

// Make changes to the sheet
sheet.getRow(2).getCell(0).setCellValue("Changed value"); // For example

// All done
FileOutputStream fileOut = new FileOutputStream("new.xls"); 
wb.write(fileOut);
fileOut.close();

If you code against the interfaces, then you can just swap between HSSF and XSSF in your constructor, and have your code work for both formats

于 2012-01-26T09:45:51.950 回答
2

我使用了 XSSF,它运行良好。

        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("template.xlsx"));           
        FileOutputStream fileOut = new FileOutputStream("new.xlsx");
        //Sheet mySheet = wb.getSheetAt(0);
        XSSFSheet sheet1 = wb.getSheet("Summary");
        XSSFRow row = sheet1.getRow(15);
        XSSFCell cell = row.getCell(3);
        cell.setCellValue("Bharthan");

        wb.write(fileOut);
        log.info("Written xls file");
        fileOut.close();

只需要在maven的pom.xml中添加这个依赖

<dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.8-beta4</version>
    </dependency>
于 2017-01-09T13:49:11.433 回答