Apache POI autoSizeColumn Resizes Incorrectly - java

I'm using Apache POI in java to create an excel file. I fill in the data then try to autosize each column, however the sizes are always wrong (and I think consistent). The first two rows are always(?) completely collapsed. When I autosize the columns in excel, it works perfectly.
No blank cells are being written (I believe) and the resizing is the last thing I do.
Here's the relevant code: This is a boiled down version without error handling, etc.
public static synchronized String storeResults(ArrayList<String> resultList, String file) {
if (resultList == null || resultList.size() == 0) {
return file;
}
FileOutputStream stream = new FileOutputStream(file);
//Create workbook and result sheet
XSSFWorkbook book = new XSSFWorkbook();
Sheet results = book.createSheet("Results");
//Write results to workbook
for (int x = 0; x < resultList.size(); x++) {
String[] items = resultList.get(x).split(PRIM_DELIM);
Row row = results.createRow(x);
for (int i = 0; i < items.length; i++) {
row.createCell(i).setCellValue(items[i]);
}
}
//Auto size all the columns
for (x = 0; x < results.getRow(0).getPhysicalNumberOfCells(); x++) {
results.autoSizeColumn(x);
}
//Write the book and close the stream
book.write(stream);
stream.flush();
stream.close();
return file;
}
I know there are a few questions out there similar, but most of them are simply a case of sizing before filling in the data. And the few that aren't are more complicated/unanswered.
EDIT: I tried using a couple different fonts and it didn't work. Which isn't too surprising, as no matter what the font either all the columns should be completely collapsed or none should be.
Also, because the font issue came up, I'm running the program on Windows 7.
SOLVED: It was a font issue. The only font that I found that worked was Serif.

Just to make an answer out of my comment. The rows couldn't size properly because Java was unaware of the font you were trying to use this link should help if you want to install new fonts into Java so you could use something fancier. It also has the list of default fonts that Java knows.
Glad this helped and you got your issue solved!

I was also running into this issue and this was my solution.
Steps:
Create workbook
Create spreadsheet
Create row
Create/Set font to "Arial"
Create/Set style with font
Create/Set cell with value and style
autoSizeColumn
Create File
Code:
// initialize objects
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet(sheetName);
XSSFRow row = spreadsheet.createRow(0);
XSSFCell cell;
// font/style
XSSFFont font = workbook.createFont();
font.setFontName("Arial");
XSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
// create/set cell & style
cell = row.createCell(0);
cell.setCellValue("New Cell");
cell.setCellStyle(style);
// auto size
spreadsheet.autoSizeColumn(0);
// create file
File aFile = new File("Your Filename");
FileOutputStream out = new FileOutputStream(aFile);
workbook.write(out);
Resources:
http://www.tutorialspoint.com/apache_poi/index.htm

This is probably related to this POI Bug which is related to Java Bug JDK-8013716: Renderer for Calibri and Cambria Fonts fails since update 45.
In this case changing the Font or using JRE above 6u45 / 7u21 should fix the issue.
You can also mtigitate the issue and avoid the columns from being totally collapsed by using a code like this:
sheet.autoSizeColumn(x);
if (sheet.getColumnWidth(x) == 0) {
// autosize failed use MIN_WIDTH
sheet.setColumnWidth(x, MIN_WIDTH);
}

I had a similar issue on Windows 7.
I was using the Calibri font (that is supported in my JVM).
With that font the getBounds().getWidth() of the java.awt.font.TextLayout used by the autoSizeColumn() POI method returns 0.
Changing the font to Calibri-Regular solved the issue in my case.

Here are my 2 cents -
I was using the default font (Arial in my case) using it to make certain fields bold in the xls. Worked like a charm in Windows along with autoSizeColumn() function.
Linux wasn't that forgiving. The auto-sizing was improper at places. After going through this thread and other I came up with the following solution.
I copied the Arial font's .tff files into the JAVA/jre/lib/fonts directory and re-ran the application. Worked just fine.

I've used Helvetica font trying to replace Arial font (in fact, Helvetica is similar to Arial).
XSSFFont font = wb.createFont();
font.setFontName("Helvetica");

I found that auto-sizing didn't make the column wide enough when the widest string began with spaces, e.g.
cell.setCellValue(" New Cell");
This can be fixed by using indentations instead, e.g.
// font/style
XSSFFont font = workbook.createFont();
font.setFontName("Arial");
XSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
style.setIndention((short)2);
// create/set cell & style
cell = row.createCell(0);
cell.setCellValue("New Cell");
cell.setCellStyle(style);
// auto size
spreadsheet.autoSizeColumn(0);

The following works for me.
I set the font and use autoSizeColumn() after enter all the data.
public static XSSFWorkbook createExcel(List<ChannelVodFileInfoList> resList) {
XSSFWorkbook hwb = new XSSFWorkbook();
String[] title = { "1", "2", "3", "4"};
XSSFSheet sheet = hwb.createSheet("dataStats");
XSSFRow firstrow = sheet.createRow(0);
for (int i = 0; i < title.length; i++) {
XSSFCell xh = firstrow.createCell(i);
xh.setCellValue(title[i]);
}
if (resList == null || resList.size() == 0) {
return hwb;
}
for (int i = 0; i < resList.size(); i++) {
ChannelVodFileInfoList doTemp = resList.get(i);
XSSFRow row = sheet.createRow(i + 1);
for (int j = 0; j < title.length; j++) {
XSSFCell cell = row.createCell(j);
Font font111 = hwb.createFont();
font111.setBoldweight(Font.BOLDWEIGHT_NORMAL);
XSSFCellStyle cellStyle111 = hwb.createCellStyle();
cellStyle111.setFont(font111);
cell.setCellStyle(cellStyle111);
if (j == 0) {
cell.setCellValue(dateStr);
} else if (j == 1) {
cell.setCellValue(doTemp.getChannelName());
}else if (j == 2) {
cell.setCellValue(doTemp.getBitrate());
}else if (j == 3) {
cell.setCellValue(doTemp.getWh());
}
}
for (int j = 0; j < title.length; j++) {
sheet.autoSizeColumn(j);
}
return hwb;
}

A Hacky Way
My case was after auto-sizing, those cells were slightly smaller than the width of the actual content.
What I did is just added extra 200 widths after the autoSizeColumn method is being called.
sheet.autoSizeColumn(columnIndex);
sheet.setColumnWidth(columnIndex, sheet.getColumnWidth(columnIndex) + 200);
This worked fine for me :)

In the event users are running into the issue where they have a sheet with both cells and merged cells, Gagravarr's answer on this post really helped me:
https://stackoverflow.com/a/31425163/9407809
Posting here for future users looking for this.

Related

Cell style is lost or not displayed in Excel 97-2003 (.xls)

I am using the Apache POI library to export data to Excel. I have tried all the latest versions (3.17, 4.1.2, and 5.2.1).
I have a problem with Excel 97 (.xls) format in relation to cell styles. The cell style somehow is lost (or not displayed) after a certain number of columns.
Here is my sample code:
private void exportXls() {
try (
OutputStream os = new FileOutputStream("test.xls");
Workbook wb = new HSSFWorkbook();) {
Sheet sh = wb.createSheet("test");
Row r = sh.createRow(0);
for (int i = 0; i < 50; i++) {
Cell c = r.createCell(i);
c.setCellValue(i + 1);
CellStyle cs = wb.createCellStyle();
cs.setFillBackgroundColor(IndexedColors.WHITE.index);
cs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cs.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
c.setCellStyle(cs);
}
wb.write(os);
os.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
And the result as viewed by MS Excel 2019
Viewed by MS Excel
As you can see, the style/format is lost after cell 43rd.
But, when I open the same file by other applications like XLS Viewer Free (from Microsoft Store) or Google Sheets (online), the style/format still exists and is displayed well.
Viewed by XLS Viewer Free
Viewed by Google Sheets
Could anyone please tell me what is going on here?
Did I miss something in my code?
Is there any hidden setting in MS Excel that causes this problem?
Thank you.
Creating cell styles for each single cell is not a good idea using apache poi. Cell styles are stored on workbook level in Excel. The sheets and cells share the cell styles if possible.
And there are limits for maximum count of different cell styles in all Excel versions. The limit for the binary *.xls is less than the one for the OOXML *.xlsx.
The limit alone cannot be the only reason for the result you have. But it seems as if Excel is not very happy with the 50 exactly same cell styles in workbook. Those are memory waste as only one shared style would be necessary as all the 50 cells share the same style.
Solutions are:
Do creating the cell styles on workbook level outside cell creating loops and only set the styles to the cells in the loop.
Example:
private static void exportXlsCorrect() {
try (
OutputStream os = new FileOutputStream("testCorrect.xls");
Workbook wb = new HSSFWorkbook();) {
CellStyle cs = wb.createCellStyle();
cs.setFillBackgroundColor(IndexedColors.WHITE.index);
cs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cs.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
Sheet sh = wb.createSheet("test");
Row r = sh.createRow(0);
for (int i = 0; i < 50; i++) {
Cell c = r.createCell(i);
c.setCellValue(i + 1);
c.setCellStyle(cs);
}
wb.write(os);
os.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
Sometimes it is not really possible to know all possible needed cell styles before creating the cells. Then CellUtil can be used. This has a method CellUtil.setCellStyleProperties which is able to set specific style properties to cells. Doing that new cell styles are created on workbook level only if needed. If already present, the present cell styles are used.
Example:
private static void exportXlsUsingCellUtil() {
try (
OutputStream os = new FileOutputStream("testUsingCellUtil.xls");
Workbook wb = new HSSFWorkbook();) {
Sheet sh = wb.createSheet("test");
Row r = sh.createRow(0);
for (int i = 0; i < 50; i++) {
Cell c = r.createCell(i);
c.setCellValue(i + 1);
java.util.Map<java.lang.String,java.lang.Object> properties = new java.util.HashMap<java.lang.String,java.lang.Object>();
properties.put(org.apache.poi.ss.util.CellUtil.FILL_BACKGROUND_COLOR, IndexedColors.WHITE.index);
properties.put(org.apache.poi.ss.util.CellUtil.FILL_FOREGROUND_COLOR, IndexedColors.LIGHT_BLUE.getIndex());
properties.put(org.apache.poi.ss.util.CellUtil.FILL_PATTERN, FillPatternType.SOLID_FOREGROUND);
org.apache.poi.ss.util.CellUtil.setCellStyleProperties(c, properties);
}
wb.write(os);
os.flush();
} catch (Exception e) {
e.printStackTrace();
}
}

Change background color of row with Apache POI

I try to use Apache POI to change background colors of cells in a row. I use following code to handle it in xls file, but there aren't any changes in file after execution.
FileInputStream fis = new FileInputStream(src);
HSSFWorkbook wb = new HSSFWorkbook(fis);
r = sheet.getRow(5);
CellStyle style = wb.createCellStyle();
style.setFillForegroundColor(IndexedColors.RED.getIndex());
r.setRowStyle(style);
Style for cells has to be defined like this.
HSSFCellStyle tCs = wb.createCellStyle();
tCs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
tCs.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
It has to be applied each cells, which needed this style.
for (int k = 0; k < sheet.getRow(5).getLastCellNum(); k++) {
sheet.getRow(i).getCell(k).setCellStyle(tCs);
}

Apache POI autoSizeColumn resizes to minimum width

When working with values that are formulas, I am having difficulty getting the columns to autoresize properly.
I have "solved" this by making a hidden row that has maximum values as constant strings values, but that is far from elegant and often requires evaluating the formulas in each cell to get the largest strings that are generated. While this kind of works for such a small spreadsheet, it becomes very impractical for sheets that are ~16 columns x ~6000 rows.
The following code renders as in OpenOffice.
package com.shagie.poipoc;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import java.io.FileOutputStream;
public class SimpleBug {
public static void main(String[] args) {
try {
Workbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
CellStyle style = wb.createCellStyle();
style.setDataFormat(wb.createDataFormat().getFormat("[h]:mm"));
Cell cell = row.createCell(0);
cell.setCellValue(123.12);
cell.setCellStyle(style);
row.createCell(1).setCellFormula("A1");
row.createCell(2)
.setCellFormula("TRUNC(A1) & \"d \" & TRUNC(24 * MOD(A1,1))" +
" & \"h \" & TRUNC(MOD(60 * 24 * MOD(A1,1),60)) & \"m\"");
row.createCell(3).setCellValue("foo");
for(int i = 0; i < 4; i++) {
sheet.autoSizeColumn(i);
}
wb.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related and tried:
Apache POI autoSizeColumn Resizes Incorrectly I've tried the font in the style. I got a list of all the fonts Java was aware of with
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
for(String font:e.getAvailableFontFamilyNames()) {
System.out.println(font);
}
I tried several of the fonts listed with that loop, and while OpenOffice changed the font, the columns where still sized incorrectly.
Assuming you're looking to have the correct size of the column based on the formula results, just insert the following line right before you do the autoSizeColumn, in this case before your for loop:
HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
The reason is autoSizeColumn sizes your cell based on the cached formula evaluated results and if the formula was never evaluated, it would not know what size to set for it.
Code:
...
row.createCell(3).setCellValue("foo");
HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
for (int i = 0; i < 4; i++) {
sheet.autoSizeColumn(i);
}
...
Output (in OpenOffice)

Cloning sheets between files

I have three or more excel files with different sheets among them and I need to create a new blank file with a copy (or clone) that sheets into the new file and place them in the order I need so I can fill out the respective forms with data.
How can I do this by using Jakarta POI (XSSFWorkbook)?
First up, I think you mean Apache POI - it hasn't been Apache Jakarta POI for quite a few years now...
In terms of copying sheets from one workbook to another, it can be done, but it will require some coding. First you'll want to identify the cell styles you use, and clone those across. Make sure you keep track of which source Cell Style goes to which destination Cell Style, as you don't want to keep re-creating or you'll hit the limit! CellStyle.cloneStyleFrom(CellStyle) is the method you'll want.
Then, for each source sheet, create a sheet in the target workbook. Loop over all the source rows, creating new target ones. Then loop over the cells, switch by cell type, grab the appropriate value and set it. Rinse and repeat!
FileOutputStream os = new FileOutputStream("differnetFileName")
readWorkbook.write(os);
guess we can make use of write operation to OS with diff file name will work .
This is my implementation of copying sheets from one workbook to another. I did everything as described by Gagravarr. This solution works for me. This code will work if the sheets don't have tables, etc. If the sheets contain simple text (String, boolean, int etc), formulas, this solution will work.
Workbook oldWB = new XSSFWorkbook(new FileInputStream("C:\\input.xlsx"));
Workbook newWB = new XSSFWorkbook();
CellStyle newStyle = newWB.createCellStyle(); // Need this to copy over styles from old sheet to new sheet. Next step will be processed below
Row row;
Cell cell;
for (int i = 0; i < oldWB.getNumberOfSheets(); i++) {
XSSFSheet sheetFromOldWB = (XSSFSheet) oldWB.getSheetAt(i);
XSSFSheet sheetForNewWB = (XSSFSheet) newWB.createSheet(sheetFromOldWB.getSheetName());
for (int rowIndex = 0; rowIndex < sheetFromOldWB.getPhysicalNumberOfRows(); rowIndex++) {
row = sheetForNewWB.createRow(rowIndex); //create row in this new sheet
for (int colIndex = 0; colIndex < sheetFromOldWB.getRow(rowIndex).getPhysicalNumberOfCells(); colIndex++) {
cell = row.createCell(colIndex); //create cell in this row of this new sheet
Cell c = sheetFromOldWB.getRow(rowIndex).getCell(colIndex, Row.CREATE_NULL_AS_BLANK ); //get cell from old/original WB's sheet and when cell is null, return it as blank cells. And Blank cell will be returned as Blank cells. That will not change.
if (c.getCellType() == Cell.CELL_TYPE_BLANK){
System.out.println("This is BLANK " + ((XSSFCell) c).getReference());
}
else { //Below is where all the copying is happening. First It copies the styles of each cell and then it copies the content.
CellStyle origStyle = c.getCellStyle();
newStyle.cloneStyleFrom(origStyle);
cell.setCellStyle(newStyle);
switch (c.getCellTypeEnum()) {
case STRING:
cell.setCellValue(c.getRichStringCellValue().getString());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cell.setCellValue(c.getDateCellValue());
} else {
cell.setCellValue(c.getNumericCellValue());
}
break;
case BOOLEAN:
cell.setCellValue(c.getBooleanCellValue());
break;
case FORMULA:
cell.setCellValue(c.getCellFormula());
break;
case BLANK:
cell.setCellValue("who");
break;
default:
System.out.println();
}
}
}
}
}
//Write over to the new file
FileOutputStream fileOut = new FileOutputStream("C:\\output.xlsx");
newWB.write(fileOut);
oldWB.close();
newWB.close();
fileOut.close();
If your requirement is to copy full sheets without leaving or adding anything. I think The process of elimination works better and faster then the above code. And you don't have to worry about losing formulas, drawings, tables, styles, fonts, etc.
XSSFWorkbook wb = new XSSFWorkbook("C:\\abc.xlsx");
for (int i = wb.getNumberOfSheets() - 1; i >= 0; i--) {
if (!wb.getSheetName(i).contentEquals("January")) //This is a place holder. You will insert your logic here to get the sheets that you want.
wb.removeSheetAt(i); //Just remove the sheets that don't match your criteria in the if statement above
}
FileOutputStream out = new FileOutputStream(new File("C:\\xyz.xlsx"));
wb.write(out);
out.close();

Apache POI. Copying sheets

I'm using apache poi to create an excel document. To create new sheet in workbook I write next code:
Workbook wb = new HSSFWorkbook();
Sheet sh = wb.createSheet();
this code create and add sheet to workbook. But I want to create sheet formerly and then add it to workbook. Smth like this:
Sheet sh = new HSSFSheet();
wb.addSheet(sh);
I need such thing, because I want to copy data from one sheet of one workbook to another sheet of another workbook(Workbook interface has method Sheet cloneSheet(int)). But Workbook interface doesn't have method like addSheet(Sheet sh).
Also HSSFWorkbook is final class so I can't extend it to implement add method
How can I do this?
You can't just take a Sheet object from one Workbook, and add it to a different Workbook.
What you'll need to do is to open the old workbook and the new workbooks at the same time, and create the sheet in the new workbook. Next, clone all the styles you used in the old sheet onto the new one (HSSFCellStyle has a method for cloning a style from one workbook to another). Finally, iterate over all the cells and copy them over.
You should use RangeCopier.
XSSFWorkbook workbookFrom = new XSSFWorkbook(new File("/path/to/workbookFrom.xlsx"));
XSSFSheet sheetFrom = workbookFrom.getSheetAt(0);
XSSFWorkbook workbookTo = new XSSFWorkbook(new File("/path/to/workbookTo.xlsx"));
XSSFSheet sheetTo = workbookTo.createSheet("sheet1");
workbookTo.setSheetOrder("sheet1", 0);
XSSFRangeCopier xssfRangeCopier = new XSSFRangeCopier(sheetFrom, sheetTo);
int lastRow = sheetFrom.getLastRowNum();
int lastCol = 0;
for (int i = 0; i < lastRow; i++) {
Row row = sheetFrom.getRow(i);
if (row != null) {
if (row.getLastCellNum() > lastCol) {
lastCol = row.getLastCellNum();
}
sheetTo.setDefaultRowHeight(sheetFrom.getDefaultRowHeight());
}
}
for (int j = 0; j < lastCol; j++) {
sheetTo.setColumnWidth(j, sheetFrom.getColumnWidth(j));
}
CellRangeAddress cellAddresses = new CellRangeAddress(0, lastRow, 0, lastCol);
xssfRangeCopier.copyRange(cellAddresses, cellAddresses, true, true);
workbookTo.write(new FileOutputStream(new File("/path/to/worksheetTo.xlsx")));
POI version < v4.0
Okay I tried to do what Gagravarr said above. This solution works for me. This code will work if the sheets don't have tables, etc. If the sheets contain simple text (String, boolean, int etc), formulas, this solution will work.
Workbook oldWB = new XSSFWorkbook(new FileInputStream("C:\\input.xlsx"));
Workbook newWB = new XSSFWorkbook();
CellStyle newStyle = newWB.createCellStyle(); // Need this to copy over styles from old sheet to new sheet. Next step will be processed below
Row row;
Cell cell;
for (int i = 0; i < oldWB.getNumberOfSheets(); i++) {
XSSFSheet sheetFromOldWB = (XSSFSheet) oldWB.getSheetAt(i);
XSSFSheet sheetForNewWB = (XSSFSheet) newWB.createSheet(sheetFromOldWB.getSheetName());
for (int rowIndex = 0; rowIndex < sheetFromOldWB.getPhysicalNumberOfRows(); rowIndex++) {
row = sheetForNewWB.createRow(rowIndex); //create row in this new sheet
for (int colIndex = 0; colIndex < sheetFromOldWB.getRow(rowIndex).getPhysicalNumberOfCells(); colIndex++) {
cell = row.createCell(colIndex); //create cell in this row of this new sheet
Cell c = sheetFromOldWB.getRow(rowIndex).getCell(colIndex, Row.CREATE_NULL_AS_BLANK ); //get cell from old/original WB's sheet and when cell is null, return it as blank cells. And Blank cell will be returned as Blank cells. That will not change.
if (c.getCellType() == Cell.CELL_TYPE_BLANK){
System.out.println("This is BLANK " + ((XSSFCell) c).getReference());
}
else { //Below is where all the copying is happening. First It copies the styles of each cell and then it copies the content.
CellStyle origStyle = c.getCellStyle();
newStyle.cloneStyleFrom(origStyle);
cell.setCellStyle(newStyle);
switch (c.getCellTypeEnum()) {
case STRING:
cell.setCellValue(c.getRichStringCellValue().getString());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cell.setCellValue(c.getDateCellValue());
} else {
cell.setCellValue(c.getNumericCellValue());
}
break;
case BOOLEAN:
cell.setCellValue(c.getBooleanCellValue());
break;
case FORMULA:
cell.setCellValue(c.getCellFormula());
break;
case BLANK:
cell.setCellValue("who");
break;
default:
System.out.println();
}
}
}
}
}
//Write over to the new file
FileOutputStream fileOut = new FileOutputStream("C:\\output.xlsx");
newWB.write(fileOut);
oldWB.close();
newWB.close();
fileOut.close();
If your requirement is to copy full sheets without leaving or adding anything. I think The process of elimination works better and faster then the above code. And you don't have to worry about losing formulas, drawings, tables, styles, fonts, etc.
XSSFWorkbook wb = new XSSFWorkbook("C:\\abc.xlsx");
for (int i = wb.getNumberOfSheets() - 1; i >= 0; i--) {
if (!wb.getSheetName(i).contentEquals("January")) //This is a place holder. You will insert your logic here to get the sheets that you want.
wb.removeSheetAt(i); //Just remove the sheets that don't match your criteria in the if statement above
}
FileOutputStream out = new FileOutputStream(new File("C:\\xyz.xlsx"));
wb.write(out);
out.close();
POI version >= v4.0
As of version 4.0, Cell.CELL_TYPE_BLANK and Row.CREATE_NULL_AS_BLANK don't exist (they deprecated). Use CellType.* and Row.MissingCellPolicy.* instead.

Categories