我刚刚开始使用Apache POI做一些excel阅读和写作,我遇到了一些问题。我有一个提交按钮读取表单文本字段并将其打印到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();
任何人都可以给我一些见解或指导吗?谢谢!
答案 0 :(得分:1)
您正在将数据附加到文件中。我假设您要重新创建工作表。
public FileOutputStream(String name, boolean append) throws FileNotFoundException
append - 如果为true,则将字节写入文件末尾 而不是开始
此外,请确保在重新使用文件之前关闭输入流
inp.close();
FileOutputStream fileOut = new FileOutputStream("testSheet.xls");
wb.write(fileOut);
fileOut.close();