2014-09-13 55 views
0

我正在使用Apache poi来写入到excel中并给出该文件的下载选项。但每次下载时,它都会覆盖现有文件,甚至文件大小也在增加。避免覆盖Apache poi中的xlsx文件

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

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

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

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

新文件(absolutePathToIndexJSP)

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