Not able to insert image into excelsheet - java

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.

Related

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

How put a image in a cell of excel java?

I have tried to put an image into an Excel cell with java but without much success this is the code I was working but the only thing I've done is put the image on excel sheet but not in a cell specified
XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("My Sample Excel");
//FileInputStream obtains input bytes from the image file
InputStream inputStream = new FileInputStream("C:/images/logo.png");
//Get the contents of an InputStream as a byte[].
byte[] bytes = IOUtils.toByteArray(inputStream);
//Adds a picture to the workbook
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
//close the input stream
inputStream.close();
//Returns an object that handles instantiating concrete classes
CreationHelper helper = wb.getCreationHelper();
//Creates the top-level drawing patriarch.
Drawing drawing = sheet.createDrawingPatriarch();
//Create an anchor that is attached to the worksheet
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(1);
anchor.setRow1(2);
//Creates a picture
Picture pict = drawing.createPicture(anchor, pictureIdx);
//Reset the image to the original size
pict.resize();
//Write the Excel file
FileOutputStream fileOut = null;
fileOut = new FileOutputStream("C:/data/myFile.xlsx");
wb.write(fileOut);
fileOut.close();
What you are doing already is positioning the image with the anchor to upper left cell B3 (anchor.setCol1(1);anchor.setRow1(2);). Then you already resize the image to it's native size.
If the image shall fit into the cell B3 then you must create an anchor with upper left cell and bottom right cell. And you must not resize the image to it's native size.
Example:
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
class ImageTest {
public static void main(String[] args) {
try {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("My Sample Excel");
//FileInputStream obtains input bytes from the image file
InputStream inputStream = new FileInputStream("/home/axel/Bilder/Wasserlilien.jpg");
//Get the contents of an InputStream as a byte[].
byte[] bytes = IOUtils.toByteArray(inputStream);
//Adds a picture to the workbook
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
//close the input stream
inputStream.close();
//Returns an object that handles instantiating concrete classes
CreationHelper helper = wb.getCreationHelper();
//Creates the top-level drawing patriarch.
Drawing drawing = sheet.createDrawingPatriarch();
//Create an anchor that is attached to the worksheet
ClientAnchor anchor = helper.createClientAnchor();
//create an anchor with upper left cell _and_ bottom right cell
anchor.setCol1(1); //Column B
anchor.setRow1(2); //Row 3
anchor.setCol2(2); //Column C
anchor.setRow2(3); //Row 4
//Creates a picture
Picture pict = drawing.createPicture(anchor, pictureIdx);
//Reset the image to the original size
//pict.resize(); //don't do that. Let the anchor resize the image!
//Create the Cell B3
Cell cell = sheet.createRow(2).createCell(1);
//set width to n character widths = count characters * 256
//int widthUnits = 20*256;
//sheet.setColumnWidth(1, widthUnits);
//set height to n points in twips = n * 20
//short heightUnits = 60*20;
//cell.getRow().setHeight(heightUnits);
//Write the Excel file
FileOutputStream fileOut = null;
fileOut = new FileOutputStream("myFile.xlsx");
wb.write(fileOut);
fileOut.close();
} catch (IOException ioex) {
}
}
}
If you remove the comment signs form the program rows
...
//set width to n character widths = count characters * 256
int widthUnits = 20*256;
sheet.setColumnWidth(1, widthUnits);
//set height to n points in twips = n * 20
short heightUnits = 60*20;
cell.getRow().setHeight(heightUnits);
...
you can resize the cell B3 and so the image resizes.
package com.excel;
import java.io.FileInputStream;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFPicture;
public class ExcelWriter {
private static String[] columns = {"Name", "Email", "Date Of Birth", "Salary", "Photo"};
private static List<Employee> employees = new ArrayList<>();
// Initializing employees data to insert into the excel file
static {
Calendar dateOfBirth = Calendar.getInstance();
dateOfBirth.set(1992, 7, 21);
employees.add(new Employee("Ravinath Fernandoh", "ravi#example.com",
dateOfBirth.getTime(), 1200000.0));
dateOfBirth.set(1965, 10, 15);
employees.add(new Employee("Gayathri Sirimanna", "fer#example.com",
dateOfBirth.getTime(), 1500000.0));
dateOfBirth.set(1987, 4, 18);
employees.add(new Employee("Bivon Jethmain", "bivon#example.com",
dateOfBirth.getTime(), 1800000.0));
}
public static void main(String[] args) throws IOException, InvalidFormatException {
// Create a Workbook
Workbook workbook = new XSSFWorkbook(); // new HSSFWorkbook() for generating `.xls` file
/* CreationHelper helps us create instances of various things like DataFormat,
Hyperlink, RichTextString etc, in a format (HSSF, XSSF) independent way */
CreationHelper createHelper = workbook.getCreationHelper();
// Create a Sheet
Sheet sheet = workbook.createSheet("Employee");
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.RED.getIndex());
// Create a CellStyle with the font
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// Create a Row
Row headerRow = sheet.createRow(0);
// Create cells
for (int i = 0; i < columns.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(columns[i]);
cell.setCellStyle(headerCellStyle);
}
// Create Cell Style for formatting Date
CellStyle dateCellStyle = workbook.createCellStyle();
dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd-MM-yyyy"));
// Create Other rows and cells with employees data
int rowNum = 1;
for (Employee employee : employees) {
Row row = sheet.createRow(rowNum++);
row.setHeight((short) 1000);
row.createCell(0).setCellValue(employee.getName());
row.createCell(1).setCellValue(employee.getEmail());
Cell dateOfBirthCell = row.createCell(2);
dateOfBirthCell.setCellValue(employee.getDateOfBirth());
dateOfBirthCell.setCellStyle(dateCellStyle);
row.createCell(3).setCellValue(employee.getSalary());
//============= Inserting image - START
/* Read input PNG / JPG Image into FileInputStream Object*/
InputStream my_banner_image = new FileInputStream("D:\\PB_PROJECT\\NFC School Card\\NFCREST\\web\\photo_student\\4566.png");
/* Convert picture to be added into a byte array */
byte[] bytes = IOUtils.toByteArray(my_banner_image);
/* Add Picture to Workbook, Specify picture type as PNG and Get an Index */
int my_picture_id = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
/* Close the InputStream. We are ready to attach the image to workbook now */
my_banner_image.close();
/* Create the drawing container */
XSSFDrawing drawing = (XSSFDrawing) sheet.createDrawingPatriarch();
/* Create an anchor point */
//============= Inserting image - END
//========adding image START
XSSFClientAnchor my_anchor = new XSSFClientAnchor();
/* Define top left corner, and we can resize picture suitable from there */
my_anchor.setCol1(5); //Column B
my_anchor.setRow1(rowNum-1); //Row 3
my_anchor.setCol2(6); //Column C
my_anchor.setRow2(rowNum); //Row 4
/* Invoke createPicture and pass the anchor point and ID */
XSSFPicture my_picture = drawing.createPicture(my_anchor, my_picture_id);
//========adding image END
}
// Resize all columns to fit the content size
for (int i = 0; i < columns.length; i++) {
sheet.autoSizeColumn(i);
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("poi-generated-file.xlsx");
workbook.write(fileOut);
fileOut.close();
// Closing the workbook
workbook.close();
}
}

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>

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.

Categories

Resources