2014-09-13 60 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)

你應該實例化,調用刪除方法,然後使用它。