2015-05-22 100 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