I am using Apache poi to write in to an excel and given download option to that file. But each time when I download, it's overwriting the existing file and even file size is also increasing.
I want to create a new file by same name each time.
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();
From what you're asking, you basically just want to delete the old file and create a new one each time, right?
If you're not concerned with possible collisions (two users attempting to download the same source location at the same time) then you could use this delete file method to delete the file and then create a new one. So, where you have
new File(absolutePathToIndexJSP)
You should instantiate that, call the delete method, and then use it.
Related
FileInputStream fis =new FileInputStream("D:\\Axis SwiftTrade\\Axis_swift\\Axis_swift_update\\Reports\\ScreenshotFile.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet readable_sheet = wb.getSheet("Sheet1");
System.out.println("1141");
//FileInputStream obtains input bytes from the image file
FileInputStream inputStream = new FileInputStream(scrFile);
System.out.println("1016");
//Get the contents of an InputStream as a byte[].
byte[] bytes = IOUtils.toByteArray(inputStream);
System.out.println("1020");
//Adds a picture to the workbook
int pictureIdx = wb.addPicture(bytes, wb.PICTURE_TYPE_PNG);
System.out.println("1024");
//close the input stream
inputStream.close();
//Returns an object that handles instantiating concrete classes
CreationHelper helper = wb.getCreationHelper();
System.out.println("1030");
//Creates the top-level drawing patriarch.
Drawing drawing = readable_sheet.createDrawingPatriarch();
System.out.println("1034");
//Create an anchor that is attached to the worksheet
ClientAnchor anchor = helper.createClientAnchor();
System.out.println("1038");
anchor.setCol1(1); //Column B
anchor.setCol2(2); //Column C
System.out.println("1046");
int lastrow=readable_sheet.getLastRowNum();
System.out.println("lastrow is:" + lastrow );
for(int i=1;i<=lastrow+1;i++)
{
if(readable_sheet.getRow(i)==null)
{
System.out.println("entered");
XSSFRow row1=readable_sheet.createRow(i);
System.out.println("1028");
XSSFCell C1 = row1.createCell(0);
System.out.println("1030");
C1.setCellValue("screen shot "+i);
System.out.println("1026");
anchor.setRow1(i); //Row 3
System.out.println("1028");
anchor.setRow2(i+1);//Row 4
System.out.println("1030");
//Creates a picture
Picture pict = drawing.createPicture(anchor, pictureIdx);
System.out.println("1033");
}
}//Write the Excel file...
FileOutputStream fileOut = null;
fileOut = new FileOutputStream("D:\\Axis SwiftTrade\\Axis_swift\\Axis_swift_update\\Reports\\ScreenshotFile.xlsx");
wb.write(fileOut);
fileOut.close();
trying to add multiple images into excelsheet, succeed in that, while entering multiple screenshots into excel sheet 1st screenshot is getting removed.
any solution or snippet code for adding multiple screenshots in excel sheet???unable to add multiple screenshots into excel sheet and 1st image is removed when adding multiple screenshots into excel sheetunable to add multiple screenshots into excel sheet and 1st image is removed when adding multiple screenshots into excel sheet
I have an input .xlsx file f1 and I am trying to create another file f2 using f1 after some data modification.
Currently I am trying to use apache-poi streaming api to accomplish this task. The problem is that I am unable to accomplish this task with a low memory footprint. Here is my code snippet
import com.monitorjbl.xlsx.StreamingReader;
public static void streamingWriter()
{
SXSSFWorkbook workbook = new SXSSFWorkbook(50);
workbook.setCompressTempFiles(true);
try (InputStream inputStream = new FileInputStream(new File("inputFile.xlsx"));
Workbook inputWorkbook = StreamingReader.builder()
.rowCacheSize(50)
.bufferSize(512)
.open(inputStream)) {
Runtime runtime = Runtime.getRuntime();
Sheet newSheet;
Row newRow;
Cell newCell;
for (Sheet sheet : inputWorkbook) {
newSheet = workbook.createSheet();
for (Row row : sheet) {
newRow = newSheet.createRow(row.getRowNum());
for (Cell cell : row) {
newCell = newRow.createCell(cell.getColumnIndex());
copyCell(cell, newCell, workbook);
}
}
}
System.out.println("Mem2: " + (runtime.totalMemory() - runtime.freeMemory()));
String fileName = "outputFile.xlsx";
FileOutputStream outputStream = new FileOutputStream(fileName);
workbook.write(outputStream);
System.out.println("Mem3: " + (runtime.totalMemory() - runtime.freeMemory()));
outputStream.flush();
outputStream.close();
workbook.dispose();
} catch (IOException e) {
System.out.println("error releasing respurces: " + e.getClass().getSimpleName() +
e.getMessage());
}
}
Here are the run results -
Mem1: 112MB
Mem2: 464MB
Mem3: 697MB
Size of original "inputFile.xlsx" is 223KB.
As can be seen from the run results, calling workbook.write() is taking a lot of memory, is there a way to write to an excel file without using extra memory.
Main goal is to reduce both Mem2 and Mem3 of run results.
I am trying to export my SQLite database into a Excel file using Apache POI. I can export all string and double type values. But there have images(Blob files) on it. How can I export them together on the same Excel file and import them back?
Here is the code what I was implementing to store String and Double type values:
String query = "select * from CarOwnerDB";
preparedStatement = connection.prepareStatement(query);
rs = preparedStatement.executeQuery();
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("Car Owner Details");
XSSFRow header = sheet.createRow(0);
header.createCell(0).setCellValue("Name");
header.createCell(1).setCellValue("Username");
header.createCell(2).setCellValue("Password");
header.createCell(3).setCellValue("Company ID");
header.createCell(4).setCellValue("NID");
header.createCell(5).setCellValue("Bank Account Number");
header.createCell(6).setCellValue("Bank Name");
header.createCell(7).setCellValue("Permanent Address");
header.createCell(8).setCellValue("Present Address");
header.createCell(9).setCellValue("Phone");
header.createCell(10).setCellValue("Email");
header.createCell(11).setCellValue("Date Of Birth");
header.createCell(12).setCellValue("Age");
header.createCell(13).setCellValue("Gender");
header.createCell(14).setCellValue("Maritial Status");
header.createCell(15).setCellValue("Profile Picture");
header.createCell(16).setCellValue("Balance");
int index = 1;
while (rs.next())
{
XSSFRow row = sheet.createRow(index);
row.createCell(0).setCellValue(rs.getString("name"));
row.createCell(1).setCellValue(rs.getString("username"));
row.createCell(2).setCellValue(rs.getString("password"));
row.createCell(3).setCellValue(rs.getString("comID"));
row.createCell(4).setCellValue(rs.getString("nid"));
row.createCell(5).setCellValue(rs.getString("bankAccountNumber"));
row.createCell(6).setCellValue(rs.getString("bankName"));
row.createCell(7).setCellValue(rs.getString("permanentAddress"));
row.createCell(8).setCellValue(rs.getString("presentAddress"));
row.createCell(9).setCellValue(rs.getString("phone"));
row.createCell(10).setCellValue(rs.getString("email"));
row.createCell(11).setCellValue(rs.getString("dob"));
row.createCell(12).setCellValue(rs.getInt("age"));
row.createCell(13).setCellValue(rs.getString("gender"));
row.createCell(14).setCellValue(rs.getString("maritialStatus"));
row.createCell(15).setCellValue(rs.getBlob("profilePicture"));
row.createCell(16).setCellValue(rs.getDouble("balance"));
index++;
}
FileOutputStream fout = new FileOutputStream(
System.getProperty("user.home") + "/Desktop/" + "Car Owner Database.xlsx");
wb.write(fout);
fout.close();
preparedStatement.close();
rs.close();
In the line
row.createCell(15).setCellValue(rs.getBlob("profilePicture"));
I have image file. How can I store and retrieve those on the same Excel sheet?
Now I know how to get byte array with the image data from a SQL blob field. But don't know how to store them all using loop and array (To store string values here I used "XSSFRow row = sheet.createRow(index)").
Now I am able to store one image file by implementing this code:
InputStream is = new FileInputStream("a.png");
byte[] bytes = IOUtils.toByteArray(is);
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
is.close();
CreationHelper helper = wb.getCreationHelper();
XSSFSheet sheet1 = wb.createSheet("Car Owner Pictures");
Drawing drawing = sheet1.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(3);
anchor.setRow1(2);
Picture pict = drawing.createPicture(anchor, pictureIdx);
pict.resize();
String FileName = "Car Owner Database.xlsx";
FileOutputStream fout = new FileOutputStream(Main.getDirectory() + "/" + FileName);
wb.write(fout);
fout.close();
How can I add multiple images(same number I have created row)?
I'm trying to insert an image into a cell in Excel. I've added pictures fine, but I still runs anywhere. I want to say that I want this column.
You can set the row and column first then set the image.
try {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("MYSheet");
InputStream inputStream = new FileInputStream("path_to_image.jpg");
byte[] imageBytes = IOUtils.toByteArray(inputStream);
int pictureureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
inputStream.close();
CreationHelper helper = workbook.getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(1);
anchor.setRow1(2);
drawing.createPicture(anchor, pictureureIdx);
FileOutputStream fileOut = null;
fileOut = new FileOutputStream("output.xlsx");
workbook.write(fileOut);
fileOut.close();
}catch (Exception e) {
System.out.println(e);
}
I had some problems positioning image inside excel sheet. Here is the code which worked for me (Microsoft Excel 2019 version 2110)
public static void main(String[] args) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
Path imagePath = Path.of("...path to your image...");
byte[] imageContent = Files.readAllBytes(imagePath);
int pictureIndex = workbook.addPicture(imageContent, Workbook.PICTURE_TYPE_PNG);
// Option 1: use constructor, parameters 5-8 define starting cell-row and ending cell-row for image position
// I have no clue what first 4 parameters are doing
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 3, 3, 6, 12);
// Option 2: use Creation Helper and setters for defining starting and ending cell
XSSFClientAnchor anchor = workbook.getCreationHelper().createClientAnchor();
anchor.setCol1(3);
anchor.setRow1(3);
anchor.setCol2(6);
anchor.setRow1(12);
XSSFDrawing drawingPatriarch = sheet.createDrawingPatriarch();
drawingPatriarch.createPicture(anchor, pictureIndex);
workbook.write(new FileOutputStream("output.xlsx"));
}
Maven dependency
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.1.0</version>
</dependency>
I want to create an Excel file with a dynamic logo and a list of dynamic images.
The creation of the text part in the Excel file works great with jxls.
But I'm not able to insert one image in each row with jxls.
Please, does anyone have advice for me?
Thank you in advance.
The only solution I found was to create the XLS file with JXLS and after creating the workbook insert the images with native POI functions like :
Workbook resultWorkbook = transformer.transformXLS(is, beans);
Iterator rowIter = resultWorkbook.getSheetAt(0).rowIterator();
while (rowIter.hasNext()){
HSSFRow row = (HSSFRow) rowIter.next();
Iterator cellIter = row.cellIterator();
while (cellIter.hasNext()){
HSSFCell cell = (HSSFCell) cellIter.next();
final String IMG_PREFIX = "#IMG#";
if(cell.toString().startsWith(IMG_PREFIX)){
String cellValue = cell.toString();
cell.setCellValue("");
String imagePath = cellValue.replaceFirst(IMG_PREFIX, "");
File imageFile = new File(imagePath);
if(imageFile.exists()){
FileInputStream isi = new FileInputStream(imageFile);
ImageTools imageTools = new ImageTools();
byte[] imgBytes = imageTools.resizeImage(isi, 100);
int pictureIdx = resultWorkbook.addPicture(imgBytes, Workbook.PICTURE_TYPE_JPEG);
CreationHelper helper = resultWorkbook.getCreationHelper();
Drawing drawing = resultWorkbook.getSheetAt(0).createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(cell.getColumnIndex());
anchor.setRow1(cell.getRowIndex());
Picture pict = drawing.createPicture(anchor, pictureIdx);
pict.resize();
isi.close();
}
}
}
}
I have achieved this problem.Below are the hints:
jx:each(items="persons" var="person" lastCell="G2" direction="DOWN")
jx:image(lastCell="F2" src="person.portrait")
hope it works for you.