简体   繁体   English

使用apache poi写入xlsm(Excel 2007)

[英]write to xlsm (Excel 2007) using apache poi

I have written java file for writing xlsm(Excel 2007). 我编写了用于编写xlsm的java文件(Excel 2007)。

Using Apache POI Library, Writing xlsx file is success. 使用Apache POI库,编写xlsx文件是成功的。 And Writing xlsm file is success. 编写xlsm文件是成功的。 But I can't open the xlsm file because of error when open xlsm file. 但是由于打开xlsm文件时出错,我无法打开xlsm文件。

Would it feasible to write xlsm file using Apache POI Library? 使用Apache POI Library编写xlsm文件是否可行?

If it is feasible to write xlsm, Please kindly provide guide line How to write xlsm file using Apache poi library. 如果编写xlsm是可行的,请提供指导如何使用Apache poi库编写xlsm文件。

XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet("Related_SRC");
String realName = "Test.xlsm";
File file = new File("C:\\sdpApp", realName);
try {
    FileOutputStream fileOutput = new FileOutputStream(file);
        workBook.write(fileOutput);
        fileOutput.close();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

Thanks 谢谢

According to the documentation of Apache POI it is not possible to create macros: http://poi.apache.org/spreadsheet/limitations.html 根据Apache POI的文档,无法创建宏: http//poi.apache.org/spreadsheet/limitations.html

However it's possible to read and re-write files containing macros and apache poi will safely preserve the macros. 但是,可以读取和重写包含宏的文件,api poi将安全地保留宏。

Here is an example: 这是一个例子:

String fileName = "C:\\new_file.xlsm";

try {

    Workbook workbook;
    workbook = new XSSFWorkbook(
        OPCPackage.open("resources/template_with_macro.xlsm")
    );

    //DO STUF WITH WORKBOOK

    FileOutputStream out = new FileOutputStream(new File(fileName));
    workbook.write(out);
    out.close();
    System.out.println("xlsm created successfully..");

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (InvalidFormatException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

The file that is created will not give you an error. 创建的文件不会给您带来错误。

XLSM is Excel Spreadsheet with Macros, if you don't need macros in your sheet, you can simply use .xlsx as extension as well. XLSM是带有宏的Excel电子表格,如果您的工作表中不需要宏,您也可以简单地使用.xlsx作为扩展。

You could also produce an .xls file (ie older format) via HSSFWorkbook, Excel should be able to open .xls just fine. 您也可以通过HSSFWorkbook生成.xls文件(即旧格式),Excel应该可以打开.xls就好了。 Only limitation with this approach is that .xls is limited in the number of rows to 65k. 这种方法的唯一限制是.xls的行数限制为65k。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM