2017-01-26 105 views
0

我想寫使用Apache POI到Excel。代碼(下面)執行得很好,但是當我試圖打開excel時,它顯示excel中的數據已損壞,無法打開。寫作到Excel使用Apache POI破壞的Excel文件

Excel版本:Microsoft Office Excel中2007和Microsoft Office Excel 2003(試用過)

的Apache POI版本:3.6

import java.io.FileOutputStream; 
import java.io.IOException; 

import org.apache.poi.xssf.usermodel.XSSFCell; 
import org.apache.poi.xssf.usermodel.XSSFRow; 
import org.apache.poi.xssf.usermodel.XSSFSheet; 
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 

public class WriteExcel{ 

    public String FilePath; 
    XSSFWorkbook wb= null; 
    XSSFSheet ws= null; 
    XSSFRow xr=null; 
    XSSFCell xc=null; 
    FileOutputStream fout = null; 

    public WriteExcel(String FilePath) throws IOException 

    { 
     this.FilePath=FilePath; 
     fout=new FileOutputStream(FilePath); 
     wb=new XSSFWorkbook(); 
     wb.write(fout); 

    } 

    //Write to a specific Cell 

    public void writeToCell(String SheetName, int RowNum, int ColNum, String Data) throws IOException 
    { 
     ws=wb.createSheet(SheetName); 
     xr=ws.createRow(RowNum); 
     xc=xr.createCell(ColNum); 
     xc.setCellValue(Data); 
     fout.close(); 
    } 


    public static void main(String[] args) throws IOException { 

     WriteExcel WE= new WriteExcel("E://Learning//Learning//SoapUI//TestFiles//Write.xls"); 
     WE.writeToCell("Sheet1", 2, 2, "Pi"); 
     System.out.println("Written"); 

    } 


} 

Image1; Image2; Image3

我相信代碼是好的,因爲每次我執行代碼時,「修改日期」顯示的是最新的時間戳;所以我懷疑Microsoft Office(Excel)或Apache POI的版本可能存在某些問題。

你能幫忙嗎?

回答

2

您需要在創建表,行和單元格後,您的Excel寫入磁盤。

public WriteExcel(String FilePath) throws IOException 

{ 
    this.FilePath=FilePath; 
} 

//Write to a specific Cell 

public void writeToCell(String SheetName, int RowNum, int ColNum, String Data) throws IOException 
{ 
    fout=new FileOutputStream(FilePath); 
    wb=new XSSFWorkbook(); 
    ws=wb.createSheet(SheetName); 
    xr=ws.createRow(RowNum); 
    xc=xr.createCell(ColNum); 
    xc.setCellValue(Data); 
    wb.write(fout); 
    fout.close(); 
} 
+0

謝謝!有用。 –