2015-05-22 99 views
7

我不知道爲什麼使用POI編寫的文件無法由Excel 2013打開,但該文件仍可由POI讀取。 (單元格值可以改變)從Apache POI無法打開文件Excel由Excel女士打開(損壞)

this是從文件

在這裏的錯誤是代碼

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(); 

感謝您的幫助!

回答

1

,我看到這裏的主要問題是:

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

相反,你必須使用:

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

由MS EXCEL是可讀的2013年

+0

HSSFWorkbook工作過於概括。 –

+0

是的..但要能夠在MS Excel 2013上打開,您需要使用... XSSFWorkbook –

+0

我的輸入文件是xls類型,輸出也是xls類型。另外,我試圖將輸出文件上傳到谷歌文檔,並沒有上傳(我認爲是因爲輸出文件已損壞) – ketelagoreng

6

有兩個問題你的代碼。首先這樣的:

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

正如Apache POI Docs, don't use an InputStream if you have a File!

其次解釋說,這樣的:

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

將爲.xlsx藥粥.xls文件只工作,不。相反,你需要使用WorkbookFactory標識類型,併爲您的格式

所以正確的工作簿,改變你的代碼

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

我仍然得到相同的錯誤,原始文件的大小爲25kb,但輸出文件的大小隻有17kb(具有相同的內容或可能有一些不同) – ketelagoreng

+0

確保你正在保存到不同的文件。 POI沒有(當前)支持就地寫入,因此它需要是不同的文件 – Gagravarr

+0

String urii = fileUri.replace(「。xls」,「0.xls」);這行更改uri和名稱文件,請幫助meeeeeee ..... :(( – ketelagoreng

0

解決:使用真正的Android設備,而不是

bluestack模擬器, 我不知道爲什麼,但它的作品!

謝謝大家:d

0

的解決方案是使用.xls擴展和NOT的.xlsx,如本answer