ApachePOI generate excel (Autosize Row) with image using Java - java

I am trying to create excel file with image in it, using apache poi. What happening is data which i filled in other cells are not appearing.
ApachePOIImageDemo.java
public class ApachePOIImageDemo {
public static void main(String[] args) {
System.out.println("------------ Start Main()-------------!");
try {
List<Car> carList = new ArrayList<Car>();
Car car1 = new Car("white","GJ01OP1324","/home/vivek/1.jpg","White Maruthi 800");
Car car2 = new Car("Black","GJ01OP1244","/home/vivek/1.jpg","Black Mercedes");
Car car3 = new Car("Red","GJ01OP244","/home/vivek/1.jpg","Red Toyota Innova");
Car car4 = new Car("Blue","MH01OP1224","/home/vivek/1.jpg","Blue Renault Datson");
carList.add(car1);
carList.add(car2);
carList.add(car3);
carList.add(car4);
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("My Sample Excel");
CreationHelper creationHelper = workbook.getCreationHelper();
int index = 0;
for (Car carInstance : carList){
int columnNumber = 0;
Row row = sheet.createRow(index);
Cell cell0 = row.createCell(columnNumber++);
cell0.setCellValue(index);
Cell cell1 = row.createCell(columnNumber++);
cell1.setCellValue(carInstance.getCarColor());
Cell cell2 = row.createCell(columnNumber++);
cell2.setCellValue(carInstance.getCarPlateNumber());
InputStream inputStream = new FileInputStream(carInstance.getCarImage());
byte[] bytes = IOUtils.toByteArray(inputStream);
int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
inputStream.close();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = creationHelper.createClientAnchor();
anchor.setCol1(3);
anchor.setRow1(index);
anchor.setCol2(4);
anchor.setRow2(index+1);
Picture picture = drawing.createPicture(anchor, pictureIdx);
columnNumber++;
Cell cell4 = row.createCell(columnNumber++);
cell4.setCellValue(carInstance.getDescription());
index++;
}
FileOutputStream fileOut = null;
fileOut = new FileOutputStream("myFile.xlsx");
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("------------ End Main() -------------!");
}
}
My Result :
Click here
I want to set auto height and width of the columns.
My images are of different sizes in practical. So I need to set auto height-width in my file.
Thank you in advance.

You can autosize your column, like this :
sheet.autoSizeColumn(numberOfYourCOlumnWithImage);

Related

how to resize image width and height in excel using apache poi in java

I used picture.resize that not worked
If the picture size is big that it become large i want that picture fit into the excel cell
if picture is big that it will resize according to the cell i want a rectange cell
here is the picture of excel sheet
enter image description here
here is the code that i write i inster data in two column and three rows
i made it static but data will come dynamically
public static void main(String[] args) throws IOException {
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("My Sheet2");
Cell cell1 = sheet.createRow(0).createCell(0);
Cell cell2 = sheet.createRow(1).createCell(0);
cell1.setCellValue("this is Image1");
cell2.setCellValue("this is Image2");
InputStream inputStream1 = new FileInputStream("src/main/resources/Image1.png");
InputStream inputStream2 = new FileInputStream("src/main/resources/Image2.png");
byte[] inputImage1 = IOUtils.toByteArray(inputStream1);
byte[] inputImage2 = IOUtils.toByteArray(inputStream2);
int inputImagePicture1 = workbook.addPicture(inputImage1 , Workbook.PICTURE_TYPE_PNG);
int inputImagePicture2 = workbook.addPicture(inputImage2 , Workbook.PICTURE_TYPE_PNG);
inputStream1.close();
inputStream2.close();
CreationHelper helper = workbook.getCreationHelper();
Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor forImage1 = helper.createClientAnchor();
ClientAnchor forImage2 = helper.createClientAnchor();
forImage1.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
forImage2.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
forImage1.setCol1(1);
forImage1.setCol2(2);
forImage1.setRow1(0);
forImage1.setRow2(1);
forImage2.setCol1(1);
forImage2.setCol2(2);
forImage2.setRow1(1);
forImage2.setRow2(2);
drawing.createPicture(forImage1 , inputImagePicture1);
drawing.createPicture(forImage2 , inputImagePicture2);
int widthUnit = 25*256;
sheet.setColumnWidth(1,widthUnit);
short heightUnit = 60*20;
cell1.getRow().setHeight(heightUnit);
cell2.getRow().setHeight(heightUnit);
for(int i=0; i<3; i++){
sheet.autoSizeColumn(i);
}
try(FileOutputStream saveExcel = new FileOutputStream("target/newWorkbook.xls")) {
workbook.write(saveExcel);
}
}
Try this
int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
CreationHelper helper = workbook.getCreationHelper();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(colStart); //Col Start
anchor.setRow1(rowStart); //Row Start
anchor.setCol2(colEnd); //Col End
anchor.setRow2(rowEnd); //Row End
//create a picture anchored to Top-Left Corner
Drawing drawing = sheet.createDrawingPatriarch();
Picture pict = drawing.createPicture(anchor, pictureIdx);
pict.resize(1);

how to write values obtained using List and Iterator in a excel file using apache poi and selenium webdriver

Hi I need to store a list of values which I obtained from a webpage using List and Iterator using selenium webdriver, I want to store/write those values in a excel sheet
Link of the website:https://www.zigwheels.com/used-car
I have obtained a list of values under popular car models and I need to store it in a excel sheet using apache poi
Coding starts here:
WebElement li=
driver.findElement(By.xpath("//span[text()='Brand and Model']//parent::div//followingsibling::div//child::div[4]/ul"));
List<WebElement> alloptions=li.findElements(By.tagName("li"));
Iterator<WebElement> itr=alloptions.iterator();
while(itr.hasNext()) {
WebElement lii=itr.next();
String list=lii.getText();
System.out.println(list);
Create file, than sheet, then rows, and fill cells in row:
public void CreateNew_Make_BeckupFile() throws IOException
{
String filePath = "filepath.xls";
File f = new File(filePath);
if (!(f.exists() && f.isFile()))
{
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();
for (int p = 0; p < listaTimova.size(); p++) {
// Create a Sheet
// Sheet sheet = workbook.createSheet("Employee");
SheetCreation (workbook, p);
}
// Write the output to a file
FileOutputStream outputStream = new FileOutputStream(filePath);
workbook.write(outputStream);
// Closing the workbook
workbook.close();
outputStream.close();
}
public void SheetCreation (Workbook workbook, int teamNumber)
{
CreationHelper createHelper = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("Sheet Name");
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.BLUE.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);
}
headerFont.setColor(IndexedColors.BLACK.getIndex());
headerCellStyle.setFont(headerFont);
for (int u = 0; u < listaTimova.get(teamNumber).listaIgracaTima.size(); u++)
{
Row headerRow2 = sheet.createRow(u + 1);
**RowCreation(headerRow2, teamNumber, u, 0);**
}
for(int i = 0; i < columns.length; i++)
{
sheet.autoSizeColumn(i);
}
}
**public void RowCreation(Row row, int teamNumber, int playerNumber, int cellNumber)**
{
row.createCell(cellNumber, CellType.STRING).setCellValue("Any value for cell");
row.createCell(cellNumber+1, CellType.STRING).setCellValue("next cell in row value...");
}

XLSX file: Unable to write to the same workbook

I have written a code to pick data for certain area in the input excel and the transpose and paste it in the output excel. This read and write are 2 separate methods, which i call from main method. However, once the code runs and the file is generated, it only shows the data written for the last write method call. As per my understanding, it has to be because, my code is creating a new workbook object every time. Though i have tried to overcome this by using static keyword in my code. Please see below for the code.
public class DataExtractor {
static FileOutputStream output = null;
static XSSFWorkbook workbook = null;
static XSSFSheet sheet = null;
static XSSFWorkbook outputWorkbook = null;
static XSSFSheet outputSheet = null;
static XSSFRow row = null;
DataFormatter dataFormatter = null;
public DataExtractor(XSSFWorkbook workbook, XSSFSheet sheet, XSSFWorkbook outputWorkbook, XSSFSheet outputSheet) {
DataExtractor.workbook = workbook;
DataExtractor.sheet = sheet;
DataExtractor.outputWorkbook = outputWorkbook;
DataExtractor.outputSheet = outputSheet;
}
private ArrayList<ArrayList<String>> fetchDataFromInputExcel(){
//code for fetching data from excel/reading excel only for some grids.
}
private ArrayList<ArrayList<String>> pasteTransposedDataIntoOutputExcel(){
//code for transposing data and pasting it into output excel/writing to excel.
}
public static void main(String args[]){
File file = new File("path of xlsx file");
workbook = new XSSFWorkbook(new FileInputStream(file));
sheet = workbook.getSheet("SHEETNAME");
outputWorkbook = new XSSFWorkbook();
outputSheet = outputWorkbook.createSheet("OUTPUT");
DataExtractor obj = new DataExtractor(workbook, sheet, outputWorkbook, outputSheet);
ArrayList<ArrayList<String>> header = dataExtractor.fetchDataFromInputExcel(//args for mentioning grid area row and col are passed here);
ArrayList<ArrayList<String>> data = dataExtractor.fetchDataFromInputExcel(//args for mentioning grid area row and col are passed here);
dataExtractor.pasteTransposedDataIntoOutputExcel(dataExtractor, data, 1, 8);
dataExtractor.pasteTransposedDataIntoOutputExcel(dataExtractor, header, 1, 1);
output = new FileOutputStream(new File("path of output.xlsx file"));
outputWorkbook.write(output);
}
}
Only dataExtractor.pasteTransposedDataIntoOutputExcel(dataExtractor, header, 1, 1) operation is performed and i do not see the data for the previous one. Please suggest.
Method for transposeAndPaste:
private boolean transposeAndPasteData(DataExtractor dataExtractor, ArrayList<ArrayList<String>> data, int startRowNum, int startColNum){
XSSFCell cell = null;
XSSFRow row = null;
outputWorkbook = dataExtractor.getOutputWorkbook();
outputSheet = dataExtractor.getOutputSheet();
try {
int startRowIndex = startRowNum - 1;
int startColIndex = startColNum - 1;
//paste data row wise
//for(int rowNum = startColNum-1; rowNum<startColNum+data.size(); rowNum++) {}
Iterator<ArrayList<String>> colItr = data.iterator();
while(colItr.hasNext()) {
row = outputSheet.createRow(startRowIndex++);
ArrayList<String> colData = colItr.next();
Iterator<String> rowItr = colData.iterator();
while(rowItr.hasNext()) {
cell = row.createCell(startColIndex++);
cell.setCellValue(rowItr.next());
}
startColIndex = startColNum - 1;
}
dataExtractor.setOutputSheet(outputSheet);
return true;
}catch(Exception e) {
e.printStackTrace();
return false;
}
Thanks,
Aman

how to read the merged formula VLOOKUP cell value using poi

i have an excel file with merged and formula cell which is using the VLOOKUP(B16,Data!$A$2:$C$7,3,0). In specific cell $40 is appearing as value. but when i try to read the value it is reading only 40 and skipping the $ part.
public static void main(String[] args) {
try {
String excelFilePath = "D:\\test\\1_sample1_UA Logo Order form update on 2016-12-06.xls";
InputStream input = new BufferedInputStream(new FileInputStream(
excelFilePath));
POIFSFileSystem fs = new POIFSFileSystem(input);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
workbook.setForceFormulaRecalculation(true);
Sheet sheet = workbook.getSheetAt(3);
Row row = sheet.getRow(15);
Cell cell = row.getCell(7);
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress region = sheet.getMergedRegion(i); // Region of
// merged
// cells
int colIndex = region.getFirstColumn();
int rowNum = region.getFirstRow();
if (region.isInRange(15, 7)) {
CellReference cellReference = new CellReference("H15");
Row row2 = sheet.getRow(cellReference.getRow());
Cell cell2 = row2.getCell(cellReference.getCol());
// formulla evaluato
FormulaEvaluator forEvaluator = workbook
.getCreationHelper().createFormulaEvaluator();
workbook.getCreationHelper().createFormulaEvaluator()
.evaluateAll();
workbook.setForceFormulaRecalculation(true);
CellValue cellValue = forEvaluator.evaluate(cell2);
System.out.println("cell string value2 :: "
+ cellValue.formatAsString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

How to populate an Excel sheet with the data from an arraylist using Apache POI

How to populate an Excel sheet with the data from an arraylist using Apache POI?
public String exporttoexcel(UserDetails user) throws Exception {
System.out.print("Inside serviceimpl.ExportToExcel method");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow((short)0);
List<UserDetails> lstUserDetail = getUserDetailList();
for (int i=0; i<lstUserDetail.size(); i++) {
UserDetails lstUserDetail1 = lstUserDetail.get(i);
String a=lstUserDetail1.getStrUserName();
System.out.print("useridddd is"+a);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue(lstUserDetail1.getStrUserId());
cell.setCellValue(lstUserDetail1.getStrUserName());
cell.setCellValue(lstUserDetail1.getStrEMail());
cell.setCellValue(lstUserDetail1.getStrUserStatus());
cell.setCellValue(lstUserDetail1.getStrUserRole());
}
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
System.out.print("file created");
return null;
}
You have created one single cell and entering all the values in a same single cell each time.
You need to take two loops. One for iterating through row and another for iterating through column. Though I have not tested... use code like below.
for(int RowNum=0; RowNum<MaxArrayLength;RowNum++){
HSSFRow row = sheet.createRow(RowNum);
for(int ColNum=0; ColNum<ArrayWidth;ColNum++){
HSSFCell cell = row.createCell(ColNum);
cell.setCellValue(ArrayList[RowNum][ColNum]);
}
}
FileOutputStream fileOut = new FileOutputStream("your file path");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("sheet name");
try {
//creating the headers
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("name");
row.createCell(1).setCellValue("Name1");
row.createCell(2).setCellValue("name2");
//get the list which u want
List<String> list = getNamesList();
int rowNum = 1;
for (Name name : list ) {
Row row1 = sheet.createRow(rowNum++);
row1.createCell(0).setCellValue((name.get..));
}
workbook.write(fileOut);
}

Categories