【发布时间】:2021-02-03 00:46:46
【问题描述】:
我有一个使用 apache poi api 写入 excel 文件的代码。问题是它每次都将新数据写入文件而不是附加数据。你能帮帮我吗?这是我的代码。
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelWrite {
public static void write(AddExcel addExcel){
try {
XSSFWorkbook workbook = new XSSFWorkbook("NG.xlsx");
XSSFSheet worksheet = workbook.createSheet("Scrap Data");
int lastRow = worksheet.getLastRowNum();
System.out.println(lastRow);
Row row = worksheet.createRow(++lastRow);
row.createCell(2).setCellValue(addExcel.getArtistName());
row.createCell(3).setCellValue(addExcel.getItemName());
row.createCell(6).setCellValue(addExcel.getOriginalPrimaryMarket());
row.createCell(7).setCellValue(addExcel.getAvgResalePrice());
row.createCell(8).setCellValue(addExcel.getPriceChangedFromPrimaryMarket());
row.createCell(9).setCellValue(addExcel.getHighestAvgBid());
row.createCell(10).setCellValue(addExcel.getLastSoldPrice());
row.createCell(11).setCellValue(addExcel.getSecondayMarketVolume());
row.createCell(12).setCellValue(addExcel.getSecondarySales());
row.createCell(13).setCellValue(addExcel.getPrimarySales());
row.createCell(14).setCellValue(addExcel.getDateCreated());
row.createCell(16).setCellValue(addExcel.getInstagramURl());
row.createCell(17).setCellValue(addExcel.getTwitterURL());
FileOutputStream out = new FileOutputStream(new File("NG.xlsx"));
workbook.write(out);
out.close();
System.out.println("Write Successfully.");
}
catch(IOException io){
System.out.println(io.getMessage());
System.out.println(io.getStackTrace());
}
}
}
【问题讨论】:
-
您的文件输出流应该处于append 模式,即便如此,我认为如果您以这种方式编写文件,文件将无法读取。最好的办法是再次使用 api 读取文件并将行/列附加到文件中,而不是将原始字节附加到文件中
-
你能把代码中的更正给我吗,我把这段代码改成了这个 FileOutputStream out = new FileOutputStream(new File("NG.xlsx"),true);,还有什么遗漏吗?
-
永远不要使用 "new FileOutputStream(new File("NG.xlsx"), true)" 因为它总是会破坏你的代码。可能与stackoverflow.com/questions/65967508/… 重复阅读所有答案,以获取有关如何在不覆盖现有数据的情况下写入新数据的提示。每次执行代码时,您都在重新创建一个新的 excel 删除旧的。另一个学习如何更新 Excel 的有用链接:stackoverflow.com/questions/65940340/…
标签: java excel apache-poi