How to properly use style format in apache-poi? - java

I am trying to format my excel generated file from my java code. This is what my code snippet looks like:
...
Row row = sheet.createRow(rowNum++);
CellStyle textCellStyle = workbook.createCellStyle();
if (rowNum % 2 == 0) {
textCellStyle.setFillBackgroundColor(IndexedColors.GREEN.getIndex());
textCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
textCellStyle.setFont(textFonts1);
} else {
textCellStyle.setFont(textFonts2);
}
cell = row.createCell(0);
cell.setCellValue(student != null ? student.getIdNumber() : "");
cell.setCellStyle(textCellStyle);
...
My expectation was all even rows will be filled with green background but the produced output was different, instead it produced black background. I already tried different color or even changing my fill pattern but i always get black.
I am using poi-3.17 and poi-ooxml-3.17, excel 2007 and java 1.6

You have set a fill pattern for the cell as FillPatternType.SOLID_FOREGROUND. But you did not set a foreground color. This means that the standard color (black) is used as the foreground color.
Try to exchange...
textCellStyle.setFillBackgroundColor(IndexedColors.GREEN.getIndex());
... with ...
textCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
... and it should render as you expect. The text in the cells should also be visible.
It seems counterintuitive to set a foreground color and fill pattern when you want to set a background though.

I'm an Apache POI newbie and don't know much about the details yet. But—in some circumstances—what follows may be useful to you.
This code...
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CellBackground {
public static void main(String[] args) throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
int rowNum = 0;
for (FillPatternType fpt : FillPatternType.values()) {
Row row = sheet.createRow(rowNum++);
Cell cell = row.createCell(0);
XSSFCellStyle textCellStyle = wb.createCellStyle();
textCellStyle.setFillBackgroundColor(IndexedColors.GREEN.getIndex());
textCellStyle.setFillPattern(fpt);
cell.setCellValue(fpt.name());
cell.setCellStyle(textCellStyle);
sheet.createRow(rowNum++).setHeightInPoints(7);
}
sheet.autoSizeColumn(0);
OutputStream fileOut = new FileOutputStream("CellBackground.xlsx");
wb.write(fileOut);
wb.close();
}
}
...will produce this output in LibreOffice Calc (Apache POI 4.0.1):

Related

Apache poi cell style with color and right alignment

Did style cell color && value right alignment like this:
XSSFColor color = new XSSFColor(new Color(43,150,150));
XSSFCellStyle cellStyle = myWorkBook.createCellStyle();
cellStyle.setFillForegroundColor(color);
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setAlignment(HorizontalAlignment.RIGHT);
//cellStyle.setAlignment(CellStyle.ALIGN_RIGHT);
Cell color working but cell value right alignment not working.
Your issue is not reproducible. Exact your code snippet works as expected using the current apache poi 4.1.1.
Let's have a Minimal, Reproducible Example to show that it really works.
Code:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.xssf.usermodel.*;
class CreateExcelCellStyleAlingmentAndColor {
public static void main(String[] args) throws Exception {
try (XSSFWorkbook workbook = new XSSFWorkbook();
FileOutputStream fileout = new FileOutputStream("./Excel.xlsx") ) {
XSSFColor color = new XSSFColor(new java.awt.Color(43,150,150), null);
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(color);
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setAlignment(HorizontalAlignment.RIGHT);
XSSFSheet sheet = workbook.createSheet();
XSSFCell cell = sheet.createRow(0).createCell(0);
cell.setCellValue("A1");
cell.setCellStyle(cellStyle);
workbook.write(fileout);
}
}
}
Result:
You see, colored and right aligned.

Read Apache POI XSSFWorkbook in Aspose cells

I'm trying to create excel file with watermark in JAVA.
I'm using below approach:
1. using Apache POI api to create excel workbook
2. consume the poi workbook in aspose cells api for adding watermar.
When i'm trying to consume POI workbook in aspose cell i'm getting error- workbook not expected. Please help, as i'm new to spring/JAVA
PFB my code:
package com.mudassir.exceltest.testExcel;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Header;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class TestExcelApplication {
private static String[] COLUMNs = {"Id", "Name", "Address", "Age"};
private static List<Customer> customers = Arrays.asList(
new Customer("1", "Jack Smith", "Massachusetts", 23),
new Customer("2", "Adam Johnson", "New York", 27),
new Customer("3", "Katherin Carter", "Washington DC", 26),
new Customer("4", "Jack London", "Nevada", 33),
new Customer("5", "Jason Bourne", "California", 36));
public static void main(String[] args) throws IOException {
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("Customers");
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setColor(IndexedColors.BLUE.getIndex());
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// Row for Header
Row headerRow = sheet.createRow(0);
// Header
for (int col = 0; col < COLUMNs.length; col++) {
if(col== 0){
Cell cell = headerRow.createCell(col);
cell.setCellValue(COLUMNs[col]);
cell.setCellStyle(headerCellStyle);
}
else{
Cell cell = headerRow.createCell(col+1);
cell.setCellValue(COLUMNs[col]);
cell.setCellStyle(headerCellStyle);
}
}
// CellStyle for Age
CellStyle ageCellStyle = workbook.createCellStyle();
ageCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("#"));
int rowIdx = 1;
for (Customer customer : customers) {
Row row = sheet.createRow(rowIdx++);
row.createCell(0).setCellValue(customer.getId());
row.createCell(2).setCellValue(customer.getName());
row.createCell(3).setCellValue(customer.getAddress());
Cell ageCell = row.createCell(4);
ageCell.setCellValue(customer.getAge());
ageCell.setCellStyle(ageCellStyle);
}
// read the image to the stream
final FileInputStream stream = new FileInputStream("image.png");
final CreationHelper helper = workbook.getCreationHelper();
final Drawing drawing = sheet.createDrawingPatriarch();
final ClientAnchor anchor = helper.createClientAnchor();
//anchor.setAnchorType( ClientAnchor.MOVE_AND_RESIZE );
final int pictureIndex =
workbook.addPicture(IOUtils.toByteArray(stream), Workbook.PICTURE_TYPE_PNG);
anchor.setCol1( 0 );
anchor.setRow1( 9 ); // same row is okay
anchor.setRow2( 11 );
anchor.setCol2( 2 );
final Picture pict = drawing.createPicture( anchor, pictureIndex );
//pict.resize();
Header header = sheet.getHeader();
header.setCenter("&[pict]");
header.setLeft("Left First Page Header");
header.setRight("Right First Page Header");
sheet.addMergedRegion(new CellRangeAddress(0,0,0,1));
sheet.addMergedRegion(new CellRangeAddress(1,1,0,1));
sheet.addMergedRegion(new CellRangeAddress(2,2,0,1));
sheet.addMergedRegion(new CellRangeAddress(3,3,0,1));
sheet.addMergedRegion(new CellRangeAddress(4,4,0,1));
com.aspose.cells.Workbook workbook1=new com.aspose.cells.Workbook(workbook);
FileOutputStream fileOut = new FileOutputStream("customerstest.xlsx");
workbook.write(fileOut);
fileOut.close();
workbook.close();
}
}
Please assist me on how can i consume POI workbook in aspose cell workbook.
Below code statement is not working, rather throwing type mismatch error:
com.aspose.cells.Workbook workbook1=new com.aspose.cells.Workbook(workbook);
Thanks
Well, Aspose.Cells and POI XSSF are different APIs with diverse architectures, both have different objects and attributes. I am not sure one can easily parse one's object in other APIs or may be he cannot do that. Aspose.Cells will read and parse valid Excel workbooks (which should follow MS Excel standards and specifications).
I think you may try to save your workbook to Excel file using POI XSSF APIs and then use Aspose.Cells to read that file. If the output file (by POI XSSF) follows MS Excel standards and specifications then it should be opened fine into MS Excel too. If it is opened fine into MS Excel then surely Aspose.Cells should also load the file fine. If you find any issue where Aspose.Cells could not read the final file, then it is an issue with Aspose.Cells. Otherwise I do not think it is an issue with Aspose.Cells. In short, you can simply save the Excel Workbook (by POI XSSF) to disk (Excel file) or streams first then use Aspose.Cells APIs to load it from disk or streams, it should work fine.
I am working as Support developer/ Evangelist at Aspose.

Java apache poi: excel cell color

I'm trying to change the background of a cell with apache poi.
I know there are a lot of answers about this, but I'm using the lastest version, (3.16) and they are all deprecated.
For example all the answers suggest that I use
CellStyle#setFillPattern(CellStyle.SOLID_FOREGROUND);
but it's deprecated entirely.
So, following the apache docs, I replaced all the deprecated functions with the new ones and came up with this MCVE:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Mcve{
public static void main(String[] args) {
//Make workbook and first sheet
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("sheet1");
//Make a style
XSSFCellStyle style = workbook.createCellStyle();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillBackgroundColor(IndexedColors.RED.getIndex());
//Fill first line
Row row = sheet.createRow(0);
int i = 0;
while (i < 5) {
Cell cell = row.createCell(i);
cell.setCellValue("TestCell " + i++);
cell.setCellStyle(style);
}
//Write to file
File f = new File("Yourfilepathhere/document.xlsx"); //<-- FILL HERE
try (FileOutputStream out = new FileOutputStream(f)) {
workbook.write(out);
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I suggest you paste it in an empty Maven project in your IDE of choice and please add these dependencies to your pom.xml:
https://pastebin.com/CXdViuW5
Now, on the lastest version of Excel, this either prints all-black cells or normal white-background cells, depending on the color.
I have tried several colors and styles, doesn't seem to be working. The text is always there, but the background just won't apply.
What am I doing wrong here guys?
Looks like bug, But you can try setting forground color instead of Background color.
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.RED.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
row.getCell(0).setCellStyle(style);
This will set your background color.
You forgot to add
cell.setCellStyle(style);
Hope it helps)
XSSFWorkbook workbook1 = new XSSFWorkbook();
XSSFCellStyle greyBackgroundBold = workbook1.createCellStyle();
greyBackgroundBold.setFont(font);
greyBackgroundBold.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
greyBackgroundBold.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

I want to arrange entire cells in specific column, instead of individual cells

I used POI and tried to arrange one entire column. But only the way I found is arrange individual cell. Although I found sheet.setDefaultColumnStyle() and tried to use this function, it doesn't work at all.
could you let me know the way of using setDefaultColumnStyle() or another way.
below code is my code to arrange individual cell.
xlsxFile = new File("data.xlsx");
wb = new XSSFWorkbook();
cellStyle = wb.createCellStyle();
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
row = sheet1.createRow(0);
cell = row.createCell(1);
cell.setCellValue("name");
cell.setCellStyle(cellStyle);
My english skill is a little awkward. Thank you for reading. If there is anything weird, please let me know.
This seems to be an bug in Apache POI. There are two issues:
First: After using Sheet.setDefaultColumnStyle with a style which defines alignments, POI does not set applyAlignment="true" in the xf element's tag in styles.xml. But it should, because only that will cause Excel to apply the alignments from that style to new cells.
Second: POI itself does not apply this style to new cells in that column. It should set s="1", where 1 is the style number, in the corresponding c tag of Sheet1.xml.
So we have to workaround:
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
class CenteredColumn {
public static void main(String[] args) {
try {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
sheet.setDefaultColumnStyle(1, cellStyle);
//Workaround 1: We set setApplyAlignment(true) into the `xf` element's tag in styles.xml.
//This causes Excel applying alignments from this style to new cells in that column.
for (int i = 0; i < ((XSSFWorkbook)wb).getStylesSource().getNumCellStyles(); i++) {
if (((XSSFWorkbook)wb).getStylesSource().getStyleAt(i).equals(cellStyle)) {
((XSSFWorkbook)wb).getStylesSource().getCellXfAt(i).setApplyAlignment(true);
}
}
Row row = sheet.getRow(0);
if (row == null) row = sheet.createRow(0);
Cell cell = row.getCell(1);
if (cell == null) cell = row.createCell(1);
cell.setCellValue("name");
//Workaround 2: We set the cellStyle to the new cell because POI will not do this itself.
cell.setCellStyle(cellStyle);
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
wb.write(fileOut);
} catch (IOException ioex) {
}
}
}

Apache poi 3.10. HSSFFONT setColor doesnt work

I try to have cells with white colored font but they always appear black, this is my code:
HSSFCellStyle estiloCabecera = wb.createCellStyle();
estiloCabecera.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
estiloCabecera.setFillPattern(CellStyle.SOLID_FOREGROUND);
HSSFFont fuenteCabecera = wb.createFont();
fuenteCabecera.setFontHeightInPoints((short)12);
fuenteCabecera.setFontName("Arial");
fuenteCabecera.setColor((short)HSSFColor.WHITE.index);
//fuenteCabecera.setColor(HSSFFont.COLOR_RED);
estiloCabecera.setFont(fuenteCabecera);
Row rowCabeceraTabla = sheet.createRow((short)3);
Cell celda = rowCabeceraTabla.createCell(0);
celda.setCellValue(new HSSFRichTextString("Id pregunta"));
celda.setCellStyle(estiloCabecera);
I dont understand why, and I have tried everything I can think of. Can anyone help, please?
As posted in my comment, your example works for me, i.e. I get a black cell with white text.
The rectangle(s) instead of the text normally points out, that you've got an encoding problem or the font is not supporting the chars. Instead of "Arial" can you try to use "Arial Unicode MS"?
I'm posting my code as an answer just for further reference ... and will update it, if we found out new details, which could solve your issue ...
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
public class ForegroundColor {
public static void main(String[] args) throws Exception {
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet();
CellStyle estiloCabecera = wb.createCellStyle();
estiloCabecera.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
estiloCabecera.setFillPattern(CellStyle.SOLID_FOREGROUND);
Font fuenteCabecera = wb.createFont();
fuenteCabecera.setFontHeightInPoints((short)12);
fuenteCabecera.setFontName("Arial");
fuenteCabecera.setColor((short)HSSFColor.WHITE.index);
//fuenteCabecera.setColor(HSSFFont.COLOR_RED);
estiloCabecera.setFont(fuenteCabecera);
Row rowCabeceraTabla = sheet.createRow((short)3);
Cell celda = rowCabeceraTabla.createCell(0);
celda.setCellValue(new HSSFRichTextString("Id pregunta"));
celda.setCellStyle(estiloCabecera);
FileOutputStream fos = new FileOutputStream("color.xls");
wb.write(fos);
fos.close();
}
}

Categories