避免在Apache poi中覆盖xlsx文件

时间:2014-09-13 03:23:05

标签: java apache-poi

我正在使用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();

1 个答案:

答案 0 :(得分:1)

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

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

  

新文件(absolutePathToIndexJSP)

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

相关问题