Apache POI unable to open embedded files - java

I am trying to embed a PDF file in an excel, I am able to embed the file but it is not opening. Excel is showing the image I had anchored to, but on click of it, nothing happens as it is just an image.
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("dr.xlsx"));
FileInputStream fs = new FileInputStream("test.pdf");
FileInputStream fs1 = new FileInputStream("download.png");
int pdf = wb.addOlePackage(IOUtils.toByteArray(fs), "text.pdf", "text.pdf", "text.pdf");
int anc = wb.addPicture(IOUtils.toByteArray(fs1), HSSFPicture.PICTURE_TYPE_PNG);
XSSFSheet sheet = wb.getSheetAt(0);
XSSFDrawing draw = sheet.createDrawingPatriarch();
ClientAnchor anchor = draw.createAnchor(0, 0, 0, 0, 1, 2, 2, 4);
anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
XSSFObjectData objectData = draw.createObjectData(anchor, pdf, anc);
objectData.getCTShape().getNvSpPr().getCNvPr().setName( "text.pdf");
objectData.getCTShape().getNvSpPr().getCNvPr().setHidden(false);

Related

unable to add multiple screenshots into excel sheet and 1st image is removed when adding multiple screenshots into excel sheet

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

Insert image in column to Excel using Apache POI

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>

Avoid overwriting xlsx file in Apache poi

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.

Insert an image in Excel through JXL or POI

I am stuck in inserting an image into an excel file. The condition is I don't want a full size image to be displayed. The image size is of the regular pixles (1280 * 1024) but in the excel I want to display around 10% of it. If someone double clicks on the image, then the full size image should be displayed. When we get out of the cell, then it should again be of the same size (10%). Any help would be really appreciated.
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("My Sample Excel");
InputStream inputStream = new FileInputStream("C:/opt/ZZEclipseWorkspace2/WFCLAuto/ScreenShots/12_Mar_2013__09_40_22PM_192.168.30.145.jpeg");
byte[] bytes = IOUtils.toByteArray(inputStream);
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
inputStream.close();
CreationHelper helper = wb.getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
//set top-left corner for the image
anchor.setCol1(1);
anchor.setRow1(2);
Picture pict = drawing.createPicture(anchor, pictureIdx);
pict.resize(0.1);
FileOutputStream fileOut = null;
fileOut = new FileOutputStream("C:/opt/ZZEclipseWorkspace2/WFCLAuto/ScreenShots/testing1.xls");
wb.write(fileOut);
fileOut.close();
Try to set the top left and bottom right corners so it only fills the section your want.
HSSFClientAnchor anchor;
anchor=new HSSFClientAnchor(0,0,0,255,(short)1,2,(short)7,10);
anchor.setAnchorType(2);
This code will put the picture in a rectangle bounded by corner 1,2 and corner 7,10. I am not sure about adding the ability to double click on it though.

jxls - create Excel file with dynamic images

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.

Categories

Resources