How refactor Apache POI create cells legacy code? - java

I wrote simple method which generate excel file using data from Order class. I use createCell() method to put the data into this cells. createCell() method use identifier on which position of sheet I want to insert data. Is there a way to generate cells for each getter of Order class using java streams?
private static void createCell(Order order, Product product, Row row) {
Cell idCell = row.createCell(0);
Cell dateCell = row.createCell(1);
Cell destinationCell = row.createCell(2);
Cell productCell = row.createCell(3);
Cell productQuantityCell = row.createCell(4);
idCell.setCellValue(order.getOrderID());
dateCell.setCellValue(String.valueOf(order.getDate()));
destinationCell.setCellValue(order.getDestination());
productCell.setCellValue(product.getProductCode());
productQuantityCell.setCellValue(product.getProductQuantity());
}

Related

Fill color of individual cells with different color Apache POI

I using something like this : I have a global variable for CellStyle
CellStyle cellStyle = workbook.createCellStyle() and trying to fill color for all cells from 4th Column.
......
var cell = row.createCell(colIndex)
if (colIndex == 4) {
cellStyle.setFillForegroundColor(HSSFColor.LIME.index);
cellStyle.setFillPattern(HSSFCellStyle.ALIGN_CENTER);
} else {
cellStyle.setFillForegroundColor(HSSFColor.WHITE.index);
cellStyle.setFillPattern(HSSFCellStyle.ALIGN_CENTER);
}
if (cell != null) {
cell.setCellStyle(cellStyle);
cell.setCellValue(value);
}
by the way I am using HSSFWorkbook and HSSFSheet for reporting.
This way it just fills entire sheet and resulting all cells got filled with LIME color!
The comment is correct CellStyle is shared and there is a limit for to create new cell styles too.
So I have created three methods for three different styles and one of them: excuse me for the xtend code down.
getCellStyle1(HSSFWorkbook sampleWorkBook) {
val font = sampleWorkBook.createFont()
font.setFontName(HSSFFont.FONT_ARIAL)
font.setColor(IndexedColors.BLACK.index)
font.setBoldweight(HSSFFont.COLOR_NORMAL)
if (commonCellStyle == null)
commonCellStyle = sampleWorkBook.createCellStyle()
commonCellStyle.setCellBorderStyle
commonCellStyle.setFillForegroundColor(HSSFColor.WHITE.index)
commonCellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND)
commonCellStyle.setFont(font)
commonCellStyle.setCellBorderStyle
return commonCellStyle
}
Similarly I have more getCellStyle2 and getCellStyle3 just create one more if found null so that the styles can be shared across various column.

Is there any way to know that the CellStyle is already present in Workbook(to reuse) using POI or to Copy only Celstyle obj not reference

I want to write some records into excel but I got to know that the maximum cell styles in XSSFWorkbook is 64000.But records exceeding more than 64000 and consider I want to apply new cellstyle to each cell or I will clone with the already existing cell style.
Even to clone I need to take default cell style workbook.createCellStyle(); but this exceeds for 64001 record which leads to java.lang.IllegalStateException: The maximum number of cell styles was exceeded..
So is there anyway in POI to know already particular cell style is
present and make use of that or when is necessary to clone/create
default cellstyle and clone.
Reason for cloning is : Sometimes column/row cellstyle and existing refered excel cellstyle may be different, so am taking default cell style and cloning col & row & cell cellstyles to it.
Even I tried to add a default style to a mapmap.put("defStyle",workbook.createCellStyle();) but this wont clone properly, because it will change at first attempt of cloning since It wont get the Object it will copy the reference even object cloning also not possible here because cellstyle doesn't implement cloneable interface.
In general it should not be necessary to create as much cell styles that they exceed the max count of possible cell styles. To format cells depending of their content, there is conditional formatting usable. Also to format rows (odd/even rows different for example) conditional formatting can be used. Also for columns.
So in general not each cell or a big amount of cells should be formatted using cell styles. Instead there should a less count of cell styles be created and then be used as default cell style or in single cases if conditional formatting really will not be possible.
In my example I have a default cell style for all cells and a single row cell style for first row (even this could be achieved using conditional formatting).
To keep the default cell style working after it is applied to all columns, it must be applied to all with apache poi new created cells. For this I have provided a method getPreferredCellStyle(Cell cell). Excel itself will apply the column (or row) cell style to new filled cells automatically.
If it is then nevertheless necessary to format single cells different, then for this CellUtil should be used. This provides "various methods that deal with style's allow you to create your CellStyles as you need them. When you apply a style change to a cell, the code will attempt to see if a style already exists that meets your needs. If not, then it will create a new style. This is to prevent creating too many styles. there is an upper limit in Excel on the number of styles that can be supported." See comments in my Example.
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.CellUtil;
import java.util.Map;
import java.util.HashMap;
public class CarefulCreateCellStyles {
public CellStyle getPreferredCellStyle(Cell cell) {
// a method to get the preferred cell style for a cell
// this is either the already applied cell style
// or if that not present, then the row style (default cell style for this row)
// or if that not present, then the column style (default cell style for this column)
CellStyle cellStyle = cell.getCellStyle();
if (cellStyle.getIndex() == 0) cellStyle = cell.getRow().getRowStyle();
if (cellStyle == null) cellStyle = cell.getSheet().getColumnStyle(cell.getColumnIndex());
if (cellStyle == null) cellStyle = cell.getCellStyle();
return cellStyle;
}
public CarefulCreateCellStyles() throws Exception {
Workbook workbook = new XSSFWorkbook();
// at first we are creating needed fonts
Font defaultFont = workbook.createFont();
defaultFont.setFontName("Arial");
defaultFont.setFontHeightInPoints((short)14);
Font specialfont = workbook.createFont();
specialfont.setFontName("Courier New");
specialfont.setFontHeightInPoints((short)18);
specialfont.setBold(true);
// now we are creating a default cell style which will then be applied to all cells
CellStyle defaultCellStyle = workbook.createCellStyle();
defaultCellStyle.setFont(defaultFont);
// maybe sone rows need their own default cell style
CellStyle aRowCellStyle = workbook.createCellStyle();
aRowCellStyle.cloneStyleFrom(defaultCellStyle);
aRowCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
aRowCellStyle.setFillForegroundColor((short)3);
Sheet sheet = workbook.createSheet("Sheet1");
// apply default cell style as column style to all columns
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol cTCol =
((XSSFSheet)sheet).getCTWorksheet().getColsArray(0).addNewCol();
cTCol.setMin(1);
cTCol.setMax(workbook.getSpreadsheetVersion().getLastColumnIndex());
cTCol.setWidth(20 + 0.7109375);
cTCol.setStyle(defaultCellStyle.getIndex());
// creating cells
Row row = sheet.createRow(0);
row.setRowStyle(aRowCellStyle);
Cell cell = null;
for (int c = 0; c < 3; c++) {
cell = CellUtil.createCell(row, c, "Header " + (c+1));
// we get the preferred cell style for each cell we are creating
cell.setCellStyle(getPreferredCellStyle(cell));
}
System.out.println(workbook.getNumCellStyles()); // 3 = 0(default) and 2 just created
row = sheet.createRow(1);
cell = CellUtil.createCell(row, 0, "centered");
cell.setCellStyle(getPreferredCellStyle(cell));
CellUtil.setAlignment(cell, HorizontalAlignment.CENTER);
System.out.println(workbook.getNumCellStyles()); // 4 = 0 and 3 just created
cell = CellUtil.createCell(row, 1, "bordered");
cell.setCellStyle(getPreferredCellStyle(cell));
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(CellUtil.BORDER_LEFT, BorderStyle.THICK);
properties.put(CellUtil.BORDER_RIGHT, BorderStyle.THICK);
properties.put(CellUtil.BORDER_TOP, BorderStyle.THICK);
properties.put(CellUtil.BORDER_BOTTOM, BorderStyle.THICK);
CellUtil.setCellStyleProperties(cell, properties);
System.out.println(workbook.getNumCellStyles()); // 5 = 0 and 4 just created
cell = CellUtil.createCell(row, 2, "other font");
cell.setCellStyle(getPreferredCellStyle(cell));
CellUtil.setFont(cell, specialfont);
System.out.println(workbook.getNumCellStyles()); // 6 = 0 and 5 just created
// until now we have always created new cell styles. but from now on CellUtil will use
// already present cell styles if they matching the needed properties.
row = sheet.createRow(2);
cell = CellUtil.createCell(row, 0, "bordered");
cell.setCellStyle(getPreferredCellStyle(cell));
properties = new HashMap<String, Object>();
properties.put(CellUtil.BORDER_LEFT, BorderStyle.THICK);
properties.put(CellUtil.BORDER_RIGHT, BorderStyle.THICK);
properties.put(CellUtil.BORDER_TOP, BorderStyle.THICK);
properties.put(CellUtil.BORDER_BOTTOM, BorderStyle.THICK);
CellUtil.setCellStyleProperties(cell, properties);
System.out.println(workbook.getNumCellStyles()); // 6 = nothing new created
cell = CellUtil.createCell(row, 1, "other font");
cell.setCellStyle(getPreferredCellStyle(cell));
CellUtil.setFont(cell, specialfont);
System.out.println(workbook.getNumCellStyles()); // 6 = nothing new created
cell = CellUtil.createCell(row, 2, "centered");
cell.setCellStyle(getPreferredCellStyle(cell));
CellUtil.setAlignment(cell, HorizontalAlignment.CENTER);
System.out.println(workbook.getNumCellStyles()); // 6 = nothing new created
FileOutputStream out = new FileOutputStream("CarefulCreateCellStyles.xlsx");
workbook.write(out);
out.close();
workbook.close();
}
public static void main(String[] args) throws Exception {
CarefulCreateCellStyles carefulCreateCellStyles = new CarefulCreateCellStyles();
}
}
Not easily. I define the styles I need ahead of time, and then apply them explicitly to each cell rather than just creating a new style for each cell. Note, I do not include borders in those pre-defined styles, just fonts, colors, and sometimes fills. For borders, I draw them on to the spreadsheet later to simplify the code.

how to move the active cell to the top left cell in the range apache poi using XSSFWorkbook?

I am trying to migrate the java excel code from JBook to XSSFWorkbook. Am not getting exact methods that are used in JBook. Some of them are:
JBook.setSelection(int row, int col, int row, int col);
JBook.setSelection(JBook.getDefinedName("some String"));
The first method explains moving the active cell to the top left cell in the range.
Is there any way to get the rowindex and column index from XSSFWorkbook object?
You can't set active cell via workbook object.
Possible options:
if you have cell object you can mark it as active: cell.setAsActiveCell();
if you work with XSSFSheet and want to set multiple cell selection: xssfSheet.setActiveCell(reference) (works with xmlbeans 2.6.0, not 2.3.0)
Reference can be set as a string: "A1:A2" or using CellReference class:
String reference = new CellReference(rowNum, colNum).formatAsString()
Is there any way to get the rowindex and column index from XSSFWorkbook object?
You can get index from the cell:
cell.getColumnIndex()
cell.getRowIndex()
I don't know what is JBook.getDefinedName("some String") but if it works with named ranges, check POI user guide: Named Ranges and Named Cells.
Did you try this way
HSSFWorkbook book1 = new HSSFWorkbook();
HSSFSheet sheet = book1.getSheet("sheetName");
int rowIndex=sheet.getLastRowNum()+1;//
int columnIndex = sheet.getRow(sheet.getLastRowNum()).getPhysicalNumberOfCells()

Creating a new cell, copies previous cell's style in Apache POI..?

In my java class I am declaring cell like:
HSSFCell cell = null;
And I am using this cell in many places to create a cell and set values, styles. Like:
cell = row.createCell(1);
cell.setCellValue("1234.00");
setCellStyle(currency, cell, workbook);
cell = row.createCell(2);
setCellValue("2445.00");
Now, surprisingly, the first cell's data format is being applied to 2nd cell.
Anyone has any idea?
I expect the 2nd cell's style to be none. And the 1st cell's style should be with the data format applied by setCellStyle() method.
But, actually I am getting both the cell values with data format applied by setCellStyle() method.
setCellStyle() method:
public void setCellStyle(String currency, HSSFCell cell, HSSFWorkbook workbook){
HSSFCellStyle cellStyle = cell.getCellStyle();//I am using cell.getStyle() because the default cell style is not null for a HSSFCell
HSSFDataFormat dataFormat = workbook.createDataFormat();
if("GBP".equalsIgnoreCase(currency)){
cellStyle.setDataFormat(dataFormat.getFormat("[$£-809]#,##0_);[Red]([$£-809]#,##0)"));
}else (){
cellStyle.setDataFormat(dataFormat.getFormat("$#,##0_);[Red]($#,##0)"));
}
}
Now that you've updated your post to show your setCellStyle method, I can see the problem. Every Cell starts out with a default CellStyle, and they all share the same default CellStyle. When you call setCellStyle for the first Cell, you are changing that default CellStyle that is shared for all cells. This means that any other cells you create, where you don't set the CellStyle have your changes. Additionally, any other time you call your own setCellStyle, it will change the default cell style again.
Instead, create a new CellStyle that only that Cell will have, using Workbook's createCellStyle method.
HSSFCellStyle cellStyle = workbook.createCellStyle();
If you intend to set multiple cells to the same cell style, then you should reuse the CellStyle objects.
It is important to create a new cell style from the workbook otherwise you can end up modifying the built in style and effecting not only this cell but other cells.

Usage of cell style

I'm working on a import module from a excel file. I have to read and check this file, if something is wrong I have to color the corrisponding cell of a color. Then I implemented the following method
public void fillCell(Workbook wb, Row row, int errorColumn){
Cell cell = row.getCell(j);
CellStyle cs = wb.createCellStyle();
cs.setFillForegroundColor((short) 10);
cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cell.setCellStyle(cs);
}
but i noted that this method changes the data format of the cell. For example if I'm coloring a cell with data value 29/03/2014 i get the colored cell but its value now is 39536, the same thing happen with the numeric value 1534000001629, also in this case i get the colored cell but if i try to change the value from 1534000001629 to 1534000001630 i get 1,534+E12.
How can I fix it?
The problem is that cell styles don't only control the colour of a cell, they also control the formatting applied to it. So, what's happening is that you're replacing a cell style that eg formats as #.#%, and instead applying one that's eg red but has no number/date formatting rules applied to it.
Cell styles are workbook scoped, so you shouldn't create one per cell, thus you should make your logic somewhat like:
// Lookup from number format to the coloured version
Map<String,CellStyle> styles = new Hashmap<String,CellStyle>();
// Method to make the cell a different colour
public void fillCell(Workbook wb, Row row, int errorColumn){
Cell cell = row.getCell(j);
// Try to find a coloured one for this data formatting
String formatStr = cell.getCellStyle().getDataFormatString();
CellStyle cs = styles.get(formatStr);
if (cs == null) {
// Need to create a new coloured one
cs = wb.createCellStyle();
cs.setFillForegroundColor((short) 10);
cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cs.setDataFormat(
wb.getCreationHelper().createDataFormat().getFormat(formatStr));
// Save this for later
styles.put(formatStr, cs);
}
// Apply the coloured form, with the format string
cell.setCellStyle(cs);
}
You could either convert it to a string if you don't need to do any date processing on it later as so:
cell.setCellType(CELL_TYPE_STRING);
therwise you may be able to do it by getting the date value from the cell into Java.Util.Date object and then saving it bacl=k:
Date date=cell.getDateCellValue();
//colour change
cell.setValue(date);
I don't have time to test this right now but let me know if it works and if not I'll look more into it.
You can get more information here

Categories

Resources