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();