Java 使用 apache poi 写入 xlsm (Excel 2007)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18350178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
write to xlsm (Excel 2007) using apache poi
提问by user2636961
I have written java file for writing xlsm(Excel 2007).
我已经编写了用于编写 xlsm(Excel 2007)的 java 文件。
Using Apache POI Library, Writing xlsx file is success. And Writing xlsm file is success. But I can't open the xlsm file because of error when open xlsm file.
使用Apache POI 库,写入xlsx 文件成功。并且写入 xlsm 文件是成功的。但是由于打开 xlsm 文件时出错,我无法打开 xlsm 文件。
Would it feasible to write xlsm file using Apache POI Library?
使用 Apache POI 库编写 xlsm 文件是否可行?
If it is feasible to write xlsm, Please kindly provide guide line How to write xlsm file using Apache poi library.
如果可以写xlsm,请提供指导线How to write xlsm file using Apache poi library。
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
谢谢
采纳答案by Dennis De Reyer
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.
但是,可以读取和重写包含宏的文件,apache 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.
创建的文件不会给你一个错误。
回答by centic
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 (i.e. older format) via HSSFWorkbook, Excel should be able to open .xls just fine. Only limitation with this approach is that .xls is limited in the number of rows to 65k.
您还可以通过 HSSFWorkbook 生成 .xls 文件(即旧格式),Excel 应该能够很好地打开 .xls。这种方法的唯一限制是 .xls 的行数限制为 65k。