如何在不擦除以前的数据的情况下将数据写入Excel表格?
问题描述:
我试着下面的代码,但不能工作properly.Any类型的建议可以理解如何在不擦除以前的数据的情况下将数据写入Excel表格?
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);
}
答
你可以试试这个
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();
答
您的问题是,你正在重新创建现有行,这被歼灭的值已经存在:
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();
不,它不工作。先前的数据被删除.. –