我从 URL 获取数据并尝试使用以下代码将行附加到现有的 excel 文件中。
if (file.exists()) {
in=new FileInputStream(new File(path));
workbook = new HSSFWorkbook(in);
sheet = workbook.getSheetAt(0);
in.close();
} else {
workbook = new HSSFWorkbook();
sheet = workbook.createSheet();
row = sheet.createRow(0);
row.createCell(0).setCellValue("keyTerm");
row.createCell(1).setCellValue("username");
row.createCell(2).setCellValue("Text");
row.createCell(3).setCellValue("Timestamp");
}
进而
int count = sheet.getLastRowNum();
for (int i = 0; i < tweets.length(); i++) {
tweet = tweets.getJSONObject(i);
count++;
row = sheet.createRow(count);
row.createCell(0).setCellValue(term);
row.createCell(1)
.setCellValue(tweet.getString("from_user"));
row.createCell(2).setCellValue(
tweets.getJSONObject(i).getString("text"));
row.createCell(3).setCellValue(
tweet.getString("created_at"));
}
该代码适用于新文件,但即使我以追加模式打开文件进行写入,现有文件也无法追加。
out = new FileOutputStream(file, true);
workbook.write(out);
out.close();