gpt4 book ai didi

java - 避免覆盖 Apache poi 中的 xlsx 文件

转载 作者:行者123 更新时间:2023-12-01 12:32:41 24 4
gpt4 key购买 nike

我正在使用 Apache poi 写入 Excel 并为该文件提供下载选项。但每次下载时,它都会覆盖现有文件,甚至文件大小也会增加。

我想每次都创建一个同名的新文件。

ServletContext servletContext = httpSession.getServletContext()
String absolutePathToIndexJSP = servletContext.getRealPath("/") + "File/filename.xlsx
FileInputStream fis = new FileInputStream(new File(absolutePathToIndexJSP));
System.out.println("file path : " + absolutePathToIndexJSP);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);

XSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(XSSFCellStyle.ALIGN_RIGHT);
XSSFRow row = sheet.createRow(0);
row.setHeight((short) 2000);
XSSFCell r1c = row.createCell(0);
row.removeCell(r1c);

r1c.setCellValue("Ptoto");

for (int s = 0; s < arrayJson.length(); s++) {
System.out.println(s);

int imageCount = s + 1;
System.out.println(imageCount);
String absolutePathToImage = servletContext.getRealPath("/") + "imgData/" + imageCount + ".jpg";

System.out.println("writing image");
System.out.println("path : " + absolutePathToImage);
InputStream inputStream = new FileInputStream(absolutePathToImage);

byte[] bytes = IOUtils.toByteArray(inputStream);
int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);

inputStream.close();
CreationHelper helper = workbook.getCreationHelper();
Drawing drawing = null;
drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();

row.removeCell(r1c);
anchor.setCol1(s + 1);
anchor.setRow1(0);

double scale = 0.11;
//Creates a picture
Picture pict = drawing.createPicture(anchor, pictureIdx);
//Reset the image to the original size
pict.resize(scale);
}

fos = new FileOutputStream(absolutePathToIndexJSP);
System.out.println("file written");
workbook.write(fos);
fos.flush();
fos.close();

最佳答案

根据您的要求,您基本上只想删除旧文件并每次创建一个新文件,对吗?

如果您不担心可能发生的冲突(两个用户同时尝试下载同一源位置),那么您可以使用 this delete file method删除该文件,然后创建一个新文件。那么,你在哪里

new File(absolutePathToIndexJSP)

您应该实例化它,调用删除方法,然后使用它。

关于java - 避免覆盖 Apache poi 中的 xlsx 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25819511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com