Insert an image in Excel through JXL or POI - java

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.

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

Apache POI write image and text excel

I am having trouble with writing image and text in a same cell and questions similar to StackOverflow
on addding image and text in same cell in excel and POI Excel HSSFPicture Image and ALT TEXT
, but the expected output is different and I cannot figure out what wrong with my code?
and expected output like as below
Here is my code;
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
//FileInputStream obtains input bytes from the image file
InputStream inputStream = new FileInputStream(k_pipe_img_file);
//Get the contents of an InputStream as a byte[].
byte[] bytes = IOUtils.toByteArray(inputStream);
//Adds a picture to the workbook
int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
//close the input stream
inputStream.close();
//Returns an object that handles instantiating concrete classes
CreationHelper helper = workbook.getCreationHelper();
//Creates the top-level drawing patriarch.
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor1 = new XSSFClientAnchor();
anchor1.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
anchor1.setCol1(1);
anchor1.setCol2(1);
anchor1.setRow1(2);
anchor1.setRow2(2);
//Creates a picture
Picture pict = drawing.createPicture(anchor1, pictureIdx);
pict.resize(1, 1);
Row row = sheet.createRow(2);
row.setHeight((short) 4000);
sheet.setColumnWidth(0, 4000);
Cell cell = row.createCell(0, CellType.STRING);
cell.setCellValue("Task 1");
sheet.setColumnWidth(1, 5000);
cell = row.createCell(1, CellType.STRING);
cell.setCellValue("Replace Kemplon-Pipe");
CellStyle style=row.getSheet().getWorkbook().createCellStyle();
style.setVerticalAlignment(VerticalAlignment.TOP);
cell.setCellStyle(style);
//Write the Excel file
FileOutputStream fileOut = new FileOutputStream(k_Task_file);
workbook.write(fileOut);
fileOut.close();
Code Output:
image occupies entire cell and text is behind the image.
Is there any possible solution?
In Excel sheets pictures are not in cells but hovers in a layer over the cells. They are anchored to the cells in the following manner:
A one cell anchor determines the upper left position of the picture. If used, the picture must be resized to its native size.
A two cell anchor determines the upper left position and the size of the picture. The first anchor determines the upper left position while the second anchor determines the bottom right position. So the size of the picture is given.
Each anchor can have a row and column given but also a dx and dy. The dx and dy will be added to the column's and row's position to determine the final position. The measurement unit for dx and dy is EMU. Apache poi provides org.apache.poi.util.Units to calculate EMU from points or pixels for example.
One of the problems is that apache poi has a method to get the width of a column in pixels while it only has a method to get the height of the row in points. So we have two different measurement units to be considered.
Another problem is that if we wants to respect the aspect ratio of the picture, then we need determining the native size of the picture file first. There are many questions/answers how to get the native size of a jpg file in Java. All answers are very complex and none is really good in my opinion.
The following example does positioning a picture over cell B3 anchored 20px from left cell border, 20pt from top cell border, in width up to 20px from right cell border and in height up to 10pt from bottom cell border.
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Units;
public class ExcelDrawImagesOverCell {
private static void drawImageOnExcelSheet(XSSFSheet sheet, int row, int col,
int left/*in px*/, int top/*in pt*/, int width/*in px*/, int height/*in pt*/, int pictureIdx) throws Exception {
CreationHelper helper = sheet.getWorkbook().getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setAnchorType(AnchorType.MOVE_AND_RESIZE);
anchor.setCol1(col); //first anchor determines upper left position
anchor.setRow1(row);
anchor.setDx1(Units.pixelToEMU(left)); //dx = left in px
anchor.setDy1(Units.toEMU(top)); //dy = top in pt
anchor.setCol2(col); //second anchor determines bottom right position
anchor.setRow2(row);
anchor.setDx2(Units.pixelToEMU(left + width)); //dx = left + wanted width in px
anchor.setDy2(Units.toEMU(top + height)); //dy= top + wanted height in pt
drawing.createPicture(anchor, pictureIdx);
}
public static void main(String[] args) throws Exception {
Workbook wb = new XSSFWorkbook();
CellStyle styleVertAlingTop = wb.createCellStyle();
styleVertAlingTop.setVerticalAlignment(VerticalAlignment.TOP);
Sheet sheet = wb.createSheet();
sheet.setColumnWidth(0, 15 * 256); //15 default characters width
sheet.setColumnWidth(1, 30 * 256); //30 default characters width
Row row = sheet.createRow(2);
row.setHeight((short)(100 * 20)); //100pt height * 20 = twips (twentieth of an inch point)
Cell cell = row.createCell(0);
cell.setCellValue("Task 1");
cell = row.createCell(1);
cell.setCellValue("Replace Kemplon-Pipe");
cell.setCellStyle(styleVertAlingTop);
InputStream is = new FileInputStream("samplePict.jpeg");
byte[] bytes = IOUtils.toByteArray(is);
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
is.close();
int left = 20; // 20px
int top = 20; // 20pt
int width = Math.round(sheet.getColumnWidthInPixels(1) - left - left); //width in px
int height = Math.round(row.getHeightInPoints() - top - 10/*pt*/); //height in pt
drawImageOnExcelSheet((XSSFSheet)sheet, 2, 1, left, top, width, height, pictureIdx);
wb.write(new FileOutputStream("ExcelDrawImagesOverCell.xlsx"));
wb.close();
}
}
Result:

Spring boot creating excel error(The filename, directory name, or volume label syntax is incorrect)]

i want to write create an excel and download it but when i add image i get following error.
[(The filename, directory name, or volume label syntax is incorrect)]
but the file is loaded if i printout its name and path it shows rite name and path
file NAME: example.png LOCATION file:\D:\blueplustech\plastocartreport\target\plastocartreport-0.0.1-SNAPSHOT.jar!\BOOT-INF\classes!\static\example.png
class:
//FileInputStream obtains input bytes from the image file
InputStream inputStream = new
FileInputStream(getClass().getResource("/static/example.png").getFile());
//Get the contents of an InputStream as a byte[].
byte[] bytes = IOUtils.toByteArray(inputStream);
//Adds a picture to the workbook
int pictureIdx = workbook.addPicture(bytes,
Workbook.PICTURE_TYPE_PNG);
//close the input stream
inputStream.close();
//Returns an object that handles instantiating concrete classes
CreationHelper helper = workbook.getCreationHelper();
//Creates the top-level drawing patriarch.
Drawing drawing = sheet.createDrawingPatriarch();
//Create an anchor that is attached to the worksheet
ClientAnchor anchor = helper.createClientAnchor();
//set top-left corner for the image
anchor.setCol1(1);
anchor.setRow1(2);
//Creates a picture
Picture pict = drawing.createPicture(anchor, pictureIdx);
//Reset the image to the original size
pict.resize();
any suggestions...?
No need to use file but getResourceAsStream instead
Instead of the
InputStream inputStream = new
FileInputStream(getClass().getResource("/static/example.png").getFile());
use
InputStream inputStream = getClass().getResourceAsStream("/static/example.png");

Error message while inserting image into excel

I am trying to display an image into an excel sheet using poi. Here's the source code :
//...reading inputStream
byte[] bytes = IOUtils.toByteArray(inputStream);
//Debugging shows that pictureIdx value is 0
int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
Drawing drawing = sheet.createDrawingPatriarch();
CreationHelper helper = workbook.getCreationHelper();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(1);
anchor.setRow1(1);
Picture pict = drawing.createPicture(anchor, pictureIdx);
//...Saving workbook
When I open the generated excel file, no image is displayed and I am getting instead this error message :
Repaired records: Drawing from /xl/drawings/drawing1.xml-Part (Drawingsform)
Any help will be more appreciated. Many Thanks.
p.s: I am using Java 8 and MS Excel 2013

Not able to insert image into excelsheet

Hi I am trying to insert image into excel in android, using the following code but not able to do so, please help !!
// Create a path where we will place our List of objects on external // storage
File file = new File(context.getExternalFilesDir(null), "abc.xls");
FileOutputStream fileOS = null;
//add picture data to this workbook.
InputStream is = text.getResources().getAssets().open("images.jpg");
byte[] bytes = IOUtils.toByteArray(is);
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
is.close();
CreationHelper helper = wb.getCreationHelper();
//create sheet
Sheet sheet = wb.createSheet();
// Create the drawing patriarch. This is the top level container for all shapes.
Drawing drawing = sheet.createDrawingPatriarch();
//add a picture shape
ClientAnchor anchor = helper.createClientAnchor();
//set top-left corner of the picture,
//subsequent call of Picture#resize() will operate relative to it
anchor.setCol1(0);
anchor.setRow1(0);
Picture pict = drawing.createPicture(anchor, pictureIdx);
//auto-size picture relative to its top-left corner
// pict.resize();
// if(wb instanceof XSSFWorkbook) file += "x";
fileOS= new FileOutputStream(file);
wb.write(fileOS);
Follow this:
FileInputStream fis = new FileInputStream(imagePath);
int b;
byte[] bytes = IOUtils.toByteArray(fis);
fis.close();
// This will insert the picture from start cell to end cell of excel
// sheet.
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0,
start.getCol(), start.getRow(), end.getCol(), end.getRow());
anchor.setAnchorType(2);
int index = wb.addPicture(bytes, HSSFWorkbook.PICTURE_TYPE_JPEG);
// Create the drawing patriarch. This is the top level container for all shapes.
Drawing patriarch = sheet.createDrawingPatriarch();
try {
HSSFPicture picture = patriarch.createPicture(anchor, index);
// picture.resize();
} catch (Exception e) {
String err = e.getMessage();
}
Here start is the starting cell reference for the left-top corner of image. Similarly, end is the ending cell reference for the left-top corner of image.
CellReference start;
CellReference end;
and Note this.
// Create the drawing patriarch. This is the top level container for all shapes.
Drawing drawing = sheet.createDrawingPatriarch();
Be wary of using this code. In case of Image insertion in the same sheet this code creates new Patriarch every time for new picture/image to be inserted. Make sure that for the second time image insertion this code picks the old Patriarch object for the particular sheet where insertion is to be done.

Categories

Resources