如何在不删除以前的数据的情况下将数据写入Excel工作表?

时间:2017-09-15 12:51:52

标签: apache-poi

我尝试了以下代码但无法正常工作。任何类型的建议都将受到赞赏

public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException {
 InputStream inp = new FileInputStream("C:\\Documents and Settings\\Administrator\\Desktop\\Read Data.xlsx");
 Workbook wb = WorkbookFactory.create(inp);
 Sheet sheet = wb.getSheetAt(0);
 Row row = sheet.getRow(1);
 Cell cell = row.getCell(0);
 cell.setCellType(cell.CELL_TYPE_STRING);
 String cellContents = cell.getStringCellValue();
 //Modify the cellContents here
 // Write the output to a file
 //cell.setCellValue(cellContents); 
 FileOutputStream fileOut = new FileOutputStream("C:\\Documents and Settings\\Administrator\\Desktop\\Read Data.xlsx");
 sheet.createRow(1).createCell(1).setCellValue(cellContents);
 wb.write(fileOut);
 fileOut.close();
 System.out.println(cellContents);
}

2 个答案:

答案 0 :(得分:0)

你可以试试这个

  InputStream inp = new FileInputStream("wb.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt([sheet index]);
Row row = sheet.getRow([row index]);
Cell cell = row.getCell([cell index]);
String cellContents = cell.getStringCellValue(); 
//Modify the cellContents here
// Write the output to a file
cell.setCellValue(cellContents); 
FileOutputStream fileOut = new FileOutputStream("wb.xls");
wb.write(fileOut);
fileOut.close();

答案 1 :(得分:0)

您的问题是您正在重新创建现有行,这会消除已存在的值:

Row row = sheet.getRow(1);
....
sheet.createRow(1).createCell(1).setCellValue(cellContents);

第一个调用取第二行,第二个调用擦除它并创建一个新行

您需要做的就是更改第二个以重新使用已经获取的现有行,并保留现有值!

像(与其他修正......一样):

 DataFormatter formatter = new DataFormatter();
 Workbook wb = WorkbookFactory.create(inp);
 Sheet sheet = wb.getSheetAt(0);
 Row row = sheet.getRow(1);
 Cell cell = row.getCell(0);
 String cellContents = formatter.formatCellValue(cell);

 //Modify the cellContents here

 row.createCell(1).setCellValue(cellContents);
 FileOutputStream fileOut = new FileOutputStream("C:\\Documents and Settings\\Administrator\\Desktop\\Read Data.xlsx");
 wb.write(fileOut);
 fileOut.close();