Java - 使用FileOutputStream将数据附加到同一Excel文件

时间:2014-11-19 06:57:57

标签: java

我正在尝试在excel文件上写入数据。但每次执行程序时,新文件都是使用新数据创建的,我甚至尝试FileOutputStream(File file, true),但excel文件抛出错误

  

" Excel完成了文件级验证和修复。这部分内容   工作簿可能已被修复或丢弃。"

以下是我正在尝试的代码。提前谢谢。

class ExcelDemo {
public static void main(String[] args) throws FileNotFoundException, IOException {

    XSSFWorkbook workbook = new XSSFWorkbook();

    XSSFSheet sheet = workbook.createSheet("Employee Data1");

    Map<String, Object[]> data = new TreeMap<String, Object[]>();

    Set<String> keyset = data.keySet();
    int rownum = 0;       
      data.put("1", new Object[]{"ID", "NAME", "LASTNAME", "AGE"});
      data.put("2", new Object[]{1, "Amit", "Shukla", "12"});
      data.put("3", new Object[]{2, "Lokesh", "Gupta", "13"});
      data.put("4", new Object[]{3, "John", "Adwards", "14"});
      data.put("5", new Object[]{4, "Brian", "Schultz", "15"});
      data.put("6", new Object[]{5, "Amit", "Shukla", "12"});

    for (String key : keyset) {
        Row row = sheet.createRow(rownum++);
        Object[] objArr = data.get(key);
        int cellnum = 0;
        for (Object obj : objArr) {
            Cell cell = row.createCell(cellnum++);
            if (obj instanceof String) {
                cell.setCellValue((String) obj);
            } else if (obj instanceof Integer) {
                cell.setCellValue((Integer) obj);
            }
        }
    }
    try {
        //Write the workbook in file system
        FileOutputStream out = new FileOutputStream("G:\\demo.xlsx", true);           
        workbook.write(out);            
        out.flush();
        out.close();
        System.out.println("demo.xlsx written successfully on disk.");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

1 个答案:

答案 0 :(得分:0)

我尝试了下面的代码

FileOutputStream out = new FileOutputStream("G:\\demo.xlsx", true)

应该写成

File yourFile = new File("G:\\demo.xlsx");           
  if (!yourFile.exists()) {
           yourFile.createNewFile();
                  }
          FileOutputStream out = new FileOutputStream(yourFile, false);
          workbook.write(out);