Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

java - write to xlsm (Excel 2007) using apache poi

I have written java file for writing xlsm(Excel 2007).

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.

Would it feasible to write xlsm file using Apache POI Library?

If it is feasible to write xlsm, Please kindly provide guide line 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to the documentation of Apache POI it is not possible to create macros: 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...