如何使用Java HSSF附加到现有的excel文件

时间:2014-03-16 19:03:29

标签: java excel apache-poi poi-hssf

我还是相对较新的Java,并拼凑了足够的代码,允许我将数据写入新的excel文件。但是,我希望它写入(追加到最后)现有文件。 prepareDataToWriteToExcel()获取一些数据以写入3列数据。

public List writeDataToExcelFile(String fileName) throws IOException {
    Map excelData = prepareDataToWriteToExcel();
    List receiversList=new  ArrayList();
    HSSFWorkbook myWorkBook = new HSSFWorkbook();
    HSSFSheet mySheet = myWorkBook.createSheet();
    HSSFRow myRow = null;
    HSSFCell myCell = null;
    Iterator it=excelData.entrySet().iterator(); 
    int rowNum=0;
    while (it.hasNext()) {
        myRow = mySheet.createRow(rowNum);
        Map.Entry pairs = (Map.Entry)it.next();
        String[]arr= (String[]) pairs.getValue();
        for (int cellNum = 0; cellNum < arr.length ; cellNum++){
            myCell = myRow.createCell((short) cellNum);
            myCell.setCellValue(arr[cellNum]);     
        }
        receiversList.add(arr[2]);
        rowNum++;
    }
    try{
        FileOutputStream out = new FileOutputStream(fileName);
        myWorkBook.write(out);
        System.out.println("WRITING TO EXCEL COMPLETED");
        out.close();
    }catch(Exception e){}  
    return receiversList;
}

1 个答案:

答案 0 :(得分:0)

我发现这是更新现有Excel工作表的一个很好的例子。如您所知,您使用要修改的文件创建工作簿。这样您就可以找到创建新列的位置并编写数据。

try {
    FileInputStream file = new FileInputStream(new File("C:\\update.xls"));

    HSSFWorkbook workbook = new HSSFWorkbook(file);
    HSSFSheet sheet = workbook.getSheetAt(0);
    Cell cell = null;

    // Find empty cell     

    // Update the value of cell

    file.close();

    FileOutputStream outFile = new FileOutputStream(new File("C:\\update.xls"));
    workbook.write(outFile);
    outFile.close();

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