Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - File Excel From Apache POI Cant Open by Ms Excel (corrupt)

I don't know why the file I write using POI cant be opened by Ms Excel 2013, but the file is still readable by POI. (cell value can be changed)

this is the error from file

here is the code

FileInputStream fis = null;
    try {
        fis = new FileInputStream(fileUri); //not error at fileUri
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String urii = fileUri.replace(".xls", "0.xls"); //not error
    File fisx = new File(urii);

    Workbook workbook = null;
        workbook = new HSSFWorkbook(fis);

    Sheet sheet = workbook.getSheetAt(0);

    Row row = sheet.getRow(0);

    Cell cell = row.getCell(0);

    String p = cell.getStringCellValue();

    TextView a = (TextView) findViewById(R.id.txtUri);

    cell.setCellValue(new String("popo"));
    String x = cell.getStringCellValue();

    TextView b = (TextView) findViewById(R.id.txtFile);

    a.setText(p);
    b.setText(x);

    OutputStream fos = null;

    fos = new FileOutputStream(fisx);
    workbook.write(fos); //main problem
    fos.flush();
    fos.close();

Thanks for your help!!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There are two issues with your code. Firstly this:

FileInputStream fis = null;
try {
    fis = new FileInputStream(fileUri);

As explained in the Apache POI Docs, don't use an InputStream if you have a File!

Secondly, this:

 Workbook workbook = null;
 workbook = new HSSFWorkbook(fis);

That will only work for .xls files, not for .xlsx ones. Instead, you need to use WorkbookFactory which identifies the type and gives you the right workbook for the format

So, change your code to be

File file = new File(fileUri);
Workbook workbook = WorkbookFactory.create(file);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...