2011-04-01 91 views
2

我正在嘗試編寫一個程序,將數據附加到Java中的Excel文件中。我起牀到下面的代碼。但它會重寫Excel文件中的內容,而不是附加到它。請幫我完成這個。在Excel文件中追加數據

public class jExcel 
{ 
    static WritableWorkbook workbook; 
    public static void main(String args[])throws Exception 
    { 
     workbook = Workbook.createWorkbook((new File("D:\\0077\\my2.xls"))); 
     WritableSheet sheet = workbook.createSheet("First Sheett",1); 
     Label label = new Label(5,2,"ssssssssss"); 
     sheet.addCell(label); 
     workbook.write(); 
     workbook.close(); 
    } 
} 

回答

5

// WRITE以XLS

WritableWorkbook workbook = Workbook.createWorkbook(new File("D:\\output.xls")); 
    WritableSheet sheet = workbook.createSheet("First Sheet", 0); 
    Label label = new Label(0, 2, "A label record"); 
    sheet.addCell(label); 
    workbook.write(); 
    workbook.close(); 

    //MODIFY XLS 

    Workbook workbook1 = Workbook.getWorkbook(new File("D:\\output.xls")); 
    WritableWorkbook copy = Workbook.createWorkbook(new File("D:\\output.xls"), workbook1); 
    WritableSheet sheet2 = copy.getSheet(0); 
    //WritableCell cell = sheet2.getWritableCell(5, 2); 

    copy.write(); 
    copy.close(); 
1

從文件打開workbook後,這樣做:

WritableWorkbook copy = Workbook.createWorkbook(
    new File(""D:\\0077\\my2_copy.xls""), 
    workbook 
); 

你會得到打開工作簿的副本。在該副本中進行所需的更改並保存。

5

而不是使用createWorkbook使用「getWorkbook(java.io.File file)」來獲得現有的Excel。 然後使用getSheet(int index)檢索適當的工作表。

對於上面檢索的工作表,使用「addCell(WritableCell cell)」將單元格附加到工作表。

Workbook workbook = Workbook.getWorkbook(new File(""D:\\0077\\my2.xls"")); 
WritableWorkbook copy = Workbook.createWorkbook(new File("output.xls"), workbook); 
WritableSheet sheet2 = copy.getSheet(1); 
Label label = new Label(5,2,"ssssssssss"); 
sheet2.addCell(label); 

你會在這裏找到很多例子。 http://www.andykhan.com/jexcelapi/tutorial.html

+0

我已經tryed,但沒有得到。你可以編輯代碼併發送.pls – 2011-04-01 04:56:25

+0

@vijesh我已經添加了一些代碼去與我的答案 – 2011-04-01 05:14:58

+0

這不適合我。 – vdolez 2014-12-22 13:31:25