2015-04-29 51 views
1

我實際上試圖將String[]複製到excel中。代碼是這樣的。無法打開excel文件。拋出「無法讀取的格式」錯誤

int ExRows = 2, ExCols = 2; 
    XSSFWorkbook wb = new XSSFWorkbook(); 
    XSSFSheet xs = wb.createSheet("Sheet"); 
    try { 
      String[] inputArr = {"Gender", "Age", "Male", "45"};    
      int val =0; 
      for(int i =0;i<ExRows;i++){ 
       XSSFRow row = xs.createRow(i); 
       for(int j=0;j<ExCols;j++){ 
        FileOutputStream DestFile = new FileOutputStream("H:\\Docs\\DestExcelRecord\\DestMedicalRecord.xls"); 
        String str = inputArr[val];       
        row.createCell(j).setCellValue(str);       
        wb.write(DestFile); 
        val= val+1; 
        DestFile.close(); 
       }     
      } 
     } 


When I try opening the file, this is the first error I get, when I click on YES, I get the second error

This is the second error that I get

確切位置在哪裏我缺少什麼?

+1

爲什麼當你創建一個'XSSFWorkbook'(你寫入的.xls文件名.xlsx)格式?你有沒有試過在'for'循環之前移動'FileOutputStream'的創建,並且在'for'循環之後寫'輸出文件?你只需要寫一次文件。 – rgettman

+0

爲.xlsx引發相同的錯誤。我曾嘗試在for循環之前創建文件。當我這樣做時,它會拋出另一個錯誤.'org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException:保存失敗:保存包時發生錯誤:部分/docProps/app.xml無法保存在流中marshaller org.apache.poi.openxml4j.opc.internal.marshallers.DefaultMarshaller @ 7c81475b' – Jilna

+0

http://stackoverflow.com/questions/21116189/how-to-fill-in-excel-file-using-java解決方案那個例外是在這個鏈接。 – Jilna

回答

1

您的代碼適用於我的POI 3.11和MS Office 2013.雖然它給出與您一樣的警告。然而使用SXSSFWorkbook會使它更容易。 org.apache.poi POI 3.11 org.apache.poi POI-OOXML 3.11 enter image description here

+0

我正在使用MS Office 2007.我將擴展名從.xlsx更改爲.xls,並再次將其更改回.xls。我不明白這是多麼合乎邏輯,但它確實解決了這個問題:) – Jilna

1

首先,修正了一些問題。 (我不想編輯你的問題)

你用PIO API的方式嗎?你好Word應用程序的工作原理?

int exRows = 2, exCols = 2; 
XSSFWorkbook wb = new XSSFWorkbook(); 
XSSFSheet xs = wb.createSheet("Sheet"); 
String input; 
FileOutputStream destFile; // declare out of try 
try { 
     destFile = new FileOutputStream("H:\\Docs\\DestExcelRecord\\DestMedicalRecord.xlsx"); 
     String[] inputArr = {"Gender", "Age", "Male", "45"};    
     int val =0; 
     for(int i =0;i<exRows;i++){ 
      XSSFRow row = xs.createRow(i); 
      for(int j=0;j<exCols;j++){ 
       String str = inputArr[i];       
       row.createCell(j).setCellValue(str);       

       val +=val; // is it val += 1;? 
      }     
     } 
     wb.write(destFile); 
    } finally { 
     destFile.close(); // close in finally 
    }