2016-09-12 97 views
-1

WEF:write to xlsm (Excel 2007) using apache poi寫一個字符串.XLSM文件

當我寫一個簡單的字符串的文件,我不能夠打開文件。錯誤 - 「Excel無法打開文件‘Test1.xlsm’,因爲文件格式或文件擴展名無效」

try { 

    Workbook workbook; 
    workbook = new XSSFWorkbook(OPCPackage.open("C:\\temp\\Test.xlsm")); 

    String content = "This is the text content"; 
    byte[] contentInBytes = content.getBytes(); 

    FileOutputStream out = new FileOutputStream("C:\\temp\\Test1.xlsm"); 
    out.write(contentInBytes); 

    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(); 
} 
+0

您認爲'out.write()'有什麼用,您爲什麼這麼認爲?我的意思是,你正在將非Excel字節寫入文件的開頭,然後你希望文件可以被Excel讀取?你爲什麼期望?在Excel文檔中,你希望文本去哪裏?單元格A1?如果是這樣,爲什麼你會期望,當你沒有指定那是你想要的? – Andreas

回答

0

我不得不使用一個FileInputStream閱讀和FileOutputStream中寫。它像一個魅力工作! 將記錄集寫入xlsm

try { 
     File file = new File("C://temp//test.xslm"); 
     FileInputStream inputStream = new FileInputStream(file); 
     Workbook wb = new XSSFWorkbook(OPCPackage.open(inputStream)); 

     Sheet sheet = wb.getSheet("Sheet1"); 
     for (int x = 1; x < 5; x++) { 
      for (int y = 0; y < 4; y++) { 
       Cell c = sheet.getRow(x).getCell(y); 
       c.setCellValue(recs.getValueAt(x - 1, y).toString()); 
      } 
     } 

     FileOutputStream fileOut = new FileOutputStream("C://temp//test.xslm"); 
     wb.write(fileOut); 
     fileOut.close(); 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (InvalidFormatException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    }