我最近才开始使用Apache POI进行一些出色的读写操作,但我遇到了一个问题。我有一个提交按钮,用于读取表单文本字段并将其打印到excel文件中:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Reservations");
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[] {"Reservation ID", "NAME", "ARRIVAL DATE", "LENGTH OF STAY","HOME ADDRESS", "EMAIL", "PHONE NUMBER" ,"RESERVATION TYPE"});
data.put("2", new Object[] {1, advanceLastField.getText(), arrivalDateForm.getText(), stayNum.getText(),advanceAddressForm.getText(), advanceEmailForm.getText(),advancePhoneForm.getText(),"D"});
Set<String> keyset = data.keySet();
int rownum = 0;
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{
FileOutputStream out = new FileOutputStream(new File("testSheet.xls"),true);
workbook.write(out);
out.close();
System.out.println("Advance Reservation succesfully written");
}catch (Exception e){
e.printStackTrace();
}
}
}
}catch(NumberFormatException e){
parsable1=false;
}
这可以正常工作,但是我的问题是稍后尝试更新excel工作表。这是我的更新代码:
FileInputStream inp = new FileInputStream(new File("testSheet.xls"));
HSSFWorkbook wb = new HSSFWorkbook(inp);
HSSFSheet sheet = wb.getSheetAt(0);
if(idLookup.getText() == "1"){
if(updateNameForm.getText()!= null){
Row row = sheet.getRow(1);
Cell cell = row.getCell(1);
cell.setCellType(CellType.STRING);
cell.setCellValue(updateNameForm.getText());
}
}
FileOutputStream fileOut = new FileOutputStream("testSheet.xls",true);
wb.write(fileOut);
fileOut.close();
谁能给我一些见识或指导?谢谢!
最佳答案
您正在将数据追加到文件。我假设您要重新创建工作表。
public FileOutputStream(String name, boolean append) throws FileNotFoundException
append-如果为true,则字节将被写入文件的末尾
而不是开始
另外,在重用文件之前,请确保关闭输入流
inp.close();
FileOutputStream fileOut = new FileOutputStream("testSheet.xls");
wb.write(fileOut);
fileOut.close();