Create Excel with Java format text - java

When I download Excel, I get cells with format Numbers I need format text en all Cells.
try {
XSSFSheet sheet = workbook.createSheet(eyelash);
XSSFFont font = workbook.createFont();
font.setColor(HSSFColor.WHITE.index);
XSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.RED.index);
String[] header = { "name","surname"};
XSSFRow rowhead = sheet.createRow((short) 0);
XSSFCell cell;
int cellnum = 0;
for (int i = 0; i < header.length; i++) {
cell = rowhead.createCell(cellnum);
cell.setCellValue(header[i]);
cell.setCellStyle(style);
cell.setCellType(XSSFCell.CELL_TYPE_STRING);
cellnum++;
}
if (data) {
int myRowData = 1;
XSSFRow row = sheet.createRow((short) myRowData);
ArrayList<GasNomination> list = this.select();
for (int i = 0; i < list.size(); i++) {
row.createCell(0).setCellValue(list.get(i).name());
row.createCell(1).setCellValue(list.get(i).surname());
myRowData++;
row = sheet.createRow((short) myRowData);
}
}
} catch (Exception ex) {
}
I tried cell.setCellType(XSSFCell.CELL_TYPE_STRING);
But when I open my Excel I see formatcell type numeric ...

You can use DataFormatter,
System.out.println("started");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(0);
cell.setCellValue(3.14159);
cell.setCellType(XSSFCell.CELL_TYPE_STRING);
XSSFDataFormat format = workbook.createDataFormat();
XSSFCellStyle style = workbook.createCellStyle();
style.setDataFormat(format.getFormat("Text"));
cell.setCellStyle(style);
workbook.write(new FileOutputStream("Test.xlsx"));
System.out.println("finished");

Related

Apache POI org.apache.poi.xssf.streaming.SXSSFWorkbook generating excel report with missing header names

I am using apache poi library to dynamically generate excel report. Previously I used HSSFWorkbook class to create excel sheet.when I generated an excel report with a large number of records I got out of memory error issue due to Garbage collection overload.due to this reason I switched org.apache.poi.xssf.streaming.SXSSFWorkbook and which resolved the previous outofmemory issue.
Here is my code for generating excel report.
public Workbook getReport(String yearLevels, List<User> userList, Map<Long, Date> map) {
Workbook wb = new SXSSFWorkbook (100);
try {
CellStyle cellStyle1;
CellStyle cellStyle2;
Sheet sheet;
HSSFRichTextString cellValue;
Row row;
Cell cell;
Font font1;
Font font2;
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
sheet = wb.createSheet("User Details Report");
sheet.setColumnWidth(0, 7000);
sheet.setColumnWidth(1, 4000);
sheet.setColumnWidth(2, 4000);
sheet.setColumnWidth(3, 4000);
sheet.setColumnWidth(4, 3000);
sheet.setColumnWidth(5, 9000);
font1 = wb.createFont();
font1.setFontHeightInPoints((short) 10);
font1.setFontName("Arial");
font1.setBold(true);
font2 = wb.createFont();
font2.setFontHeightInPoints((short) 10);
font2.setFontName("Arial");
cellStyle1 = wb.createCellStyle();
cellStyle1.setFont(font1);
cellStyle2 = wb.createCellStyle();
cellStyle2.setFont(font2);
int rowNumber = 0;
CellStyle cellStyle3 = wb.createCellStyle();
cellStyle3.setFont(font1);
cellStyle3.setAlignment(HorizontalAlignment.CENTER);
row = sheet.createRow(rowNumber);
int cellValueCount=0;
Cell userName = row.getCell(cellValueCount, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
userName.setCellValue("Username");
userName.setCellStyle(cellStyle3);
Cell firstName = row.getCell(cellValueCount++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
firstName.setCellValue("First Name");
firstName.setCellStyle(cellStyle3);
Cell lastName = row.getCell(cellValueCount++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
lastName.setCellValue("Last Name");
lastName.setCellStyle(cellStyle3);
Cell yearLevel = row.getCell(cellValueCount++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
yearLevel.setCellValue("Year Level");
yearLevel.setCellStyle(cellStyle3);
Cell paidStatus = row.getCell(cellValueCount++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
paidStatus.setCellValue("Student No");
paidStatus.setCellStyle(cellStyle3);
Cell dateTitleFulfilled = row.getCell(cellValueCount++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
dateTitleFulfilled.setCellValue("Date Fulfilled");
dateTitleFulfilled.setCellStyle(cellStyle3);
CellStyle cellStyle4 = wb.createCellStyle();
cellStyle4.setFont(font2);
cellStyle4.setAlignment(HorizontalAlignment.CENTER);
int columnNumber = 0;
for (User user : userList) {
columnNumber = 0;
rowNumber++;
row = sheet.createRow(rowNumber);
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(user.getPrincipalId());
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(user.getFirstName());
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(user.getLastName());
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;
/*cell = row.getCell(columnNumber, Row.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(user.getStudentNumber());
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;*/
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(Integer.toString(user.getYearLevel()));
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(user.getJppFulfillmentTags());
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
Date date = map.get(user.getId());
if (date != null) {
String eventDate = df1.format(date);
cellValue = new HSSFRichTextString(eventDate);
} else {
cellValue = new HSSFRichTextString("");
}
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
}
} catch (Exception e) {
logger.error("ReportService::getReport Error Report Creation ", e);
}
return wb;
}
ReportService reportService = new ReportService();
Workbook wb = reportService.getReport(yearLevelsString, userList, map);
OutputStream out = response.getOutputStream();
if (request.getParameter("exportAs") == null || !request.getParameter("exportAs").equalsIgnoreCase("xls")) {
response.setHeader("Content-Disposition", "attachment;filename=User_Report.csv");
CSVPrinter csvPrinter = reportService.writeWorkbookAsCSVToOutputStream(wb, out);
csvPrinter.flush();
csvPrinter.close();
} else {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=User_Report.xls");
wb.write(out);
out.close();
}
public CSVPrinter writeWorkbookAsCSVToOutputStream(Workbook workbook, OutputStream out) throws IOException {
CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter(out), CSVFormat.DEFAULT);
try {
if (workbook != null) {
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
csvPrinter.print(cell.getStringCellValue());
}
csvPrinter.println();
}
}
} catch (Exception e) {
logger.error("ReportService::writeWorkbookAsCSVToOutputStream Error Report Creation ", e);
}
return csvPrinter;
}
After this implementation when I download excel report with more than 100 records I am getting report without header names.
but when I download excel report with less than 100 records I am getting report with cell header name without issue.
Why I the excel report is generating without header names when excel report having more than 100 records?

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

Apply style on first n columns of a row in .xls using Apache POI

I am using POI for excel creation in java and having trouble setting styles on the table created.
As the table data is huge, setting style on each and every individual cell is consuming time. And when i use rowstyle, the styling happens on those columns outside the table as well. Is there a way to apply styling on limited columns (say first n columns) of each row in an efficient way?
public XSSFWorkbook createReport(XSSFWorkbook wb, Map<String, List<ReportDto>> sheetData){
int rowIndex = 1;
int columnIndex = 0;
int index = 1;
wb.getSheetAt(0);
XSSFRow tempRow;
XSSFCell tempCell;
wb.getSheetAt(0);
for (String hexa : sheetData.keySet()) {
List<COAReportSheet2Dto> itemList = sheetData.get(hexa);
ListIterator<COAReportSheet2Dto> itemIterator = itemList.listIterator();
while (itemIterator.hasNext()) {
COAReportSheet2Dto eachItemData = itemIterator.next();
if (!eachItemData.getGeneSymbol().equals("")) {
tempRow = wb.getSheetAt(0).createRow(rowIndex++);
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(index++);
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(eachItemData.getPosition());
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(eachItemData.getSymbol());
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(hexa);
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(eachItemData.getViperId);
tempCell = tempRow.createCell(columnIndex);
tempCell.setCellValue(eachItemData.getViperPole);
}
columnIndex = 0;
}
}
return wb;
}
I'm not sure how you are doing this, but you can do this:
public static XSSFWorkbook createReport(XSSFWorkbook wb, Map<String, List<COAReportSheet2Dto>> sheetData){
int rowIndex = 1;
int columnIndex = 0;
int index = 1;
wb.getSheetAt(0);
XSSFRow tempRow;
XSSFCell tempCell;
wb.getSheetAt(0);
// Create style
CellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
for (String hexa : sheetData.keySet()) {
List<COAReportSheet2Dto> itemList = sheetData.get(hexa);
ListIterator<COAReportSheet2Dto> itemIterator = itemList.listIterator();
while (itemIterator.hasNext()) {
COAReportSheet2Dto eachItemData = itemIterator.next();
if (!eachItemData.getGeneSymbol().equals("")) {
tempRow = wb.getSheetAt(0).createRow(rowIndex++);
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(index++);
tempCell.setCellStyle(style); // style is set only on this column
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(eachItemData.getPosition());
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(eachItemData.getSymbol());
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(hexa);
tempCell = tempRow.createCell(columnIndex++);
tempCell.setCellValue(eachItemData.getViperId());
tempCell = tempRow.createCell(columnIndex);
tempCell.setCellValue(eachItemData.getViperPole());
}
columnIndex = 0;
}
}
return wb;
}
I'm creating the CellStyle in this way:
CellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
Then you can set the style only in the columns you want. About the performance, remember to create the CellStyle only once. This way you can set the same CellStyle in every cell you want. If you create a new CellStyle for each Cell you create, your program can consume unnecessary memory.
Another way to do that is to use the setDefaultColumnStyle from Sheet:
Sheet sheet = wb.getSheetAt(0);
CellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
sheet.setDefaultColumnStyle(0, style);
sheet.setDefaultColumnStyle(1, style);

Poi Excel Unable to apply background Color

I am using POI for generating excel. I have a scenario Like i want to apply background to cell row in the table.But i am unable to do it.I have given the code below.Please tell what is the mistake in my code or is the code i am doing is correct..
Code
System.out.println("Called");
try {
XSSFWorkbook xb = new XSSFWorkbook();
XSSFSheet sheet = xb.createSheet(sheetName);
XSSFCellStyle cellStyle = xb.createCellStyle();
XSSFFont font = xb.createFont();
int rowIdx = 10;
short cellIdx = 1;
CommonUtils.getGlobalVariable("GLOBAL.M_COMP_CODE"));
int rowNo = 0;
// Row 1
XSSFCellStyle boldCellStyle = xb.createCellStyle();
XSSFFont boldFont = xb.createFont();
XSSFRow row1 = sheet.createRow(rowNo);
XSSFCell cell1 = row1.createCell(1);
boldFont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
boldFont.setColor(new XSSFColor(Color.RED));
boldCellStyle.setAlignment(CellStyle.ALIGN_CENTER);
boldCellStyle.setFont(boldFont);
cell1.setCellValue(headingName);
sheet.addMergedRegion(CellRangeAddress.valueOf("B1:I1"));
cell1.setCellStyle(boldCellStyle);
XSSFCellStyle cellStyleAmount = xb.createCellStyle();
cellStyleAmount.setAlignment(XSSFCellStyle.ALIGN_RIGHT);
rowNo++;
// Row 2
if ((String) addrDetails.get("COMP_NAME") != null) {
XSSFRow row2 = sheet.createRow(rowNo);
XSSFCell compNamecell = row2.createCell(1);
compNamecell.setCellStyle(cellStyle);
compNamecell.setCellValue("Company");
sheet.addMergedRegion(CellRangeAddress.valueOf("B2:B2"));
compNamecell = row2.createCell(2);
compNamecell
.setCellValue((String) addrDetails.get("COMP_NAME"));
sheet.addMergedRegion(CellRangeAddress.valueOf("C2:G2"));
compNamecell.setCellStyle(cellStyle);
}
rowNo++;
// Row 3
if ((String) addrDetails.get("ADDR_NAME") != null) {
XSSFRow row3 = sheet.createRow(rowNo);
XSSFCell cell = row3.createCell(1);
cell = row3.createCell(1);
cell.setCellStyle(cellStyle);
cell.setCellValue("Address ");
sheet.addMergedRegion(CellRangeAddress.valueOf("B3:B3"));
cell = row3.createCell(2);
cell.setCellValue((String) addrDetails.get("ADDR_NAME"));
sheet.addMergedRegion(CellRangeAddress.valueOf("C3:G3"));
cell.setCellStyle(cellStyle);
}
rowNo++;
if (addrDetails.get("COMP_ADD_1") != null) {
XSSFRow row4 = sheet.createRow(rowNo);
XSSFCell cell = row4.createCell(1);
cell = row4.createCell(1);
cell.setCellStyle(cellStyle);
cell.setCellValue("");
sheet.addMergedRegion(CellRangeAddress.valueOf("B4:B4"));
cell = row4.createCell(2);
cell.setCellValue((String) addrDetails.get("COMP_ADD_1"));
sheet.addMergedRegion(CellRangeAddress.valueOf("C4:G4"));
cell.setCellStyle(cellStyle);
}
rowNo++;
if (addrDetails.get("COMP_ADD_2") != null) {
XSSFRow row5 = sheet.createRow(rowNo);
XSSFCell cell = row5.createCell(1);
cell = row5.createCell(1);
cell.setCellStyle(cellStyle);
cell.setCellValue("");
sheet.addMergedRegion(CellRangeAddress.valueOf("B5:B5"));
cell = row5.createCell(2);
cell.setCellValue((String) addrDetails.get("COMP_ADD_2"));
sheet.addMergedRegion(CellRangeAddress.valueOf("C5:G5"));
cell.setCellStyle(cellStyle);
}
rowNo++;
if (addrDetails.get("COMP_ADD_3") != null) {
XSSFRow row6 = sheet.createRow(rowNo);
XSSFCell cell = row6.createCell(1);
cell = row6.createCell(1);
cell.setCellStyle(cellStyle);
cell.setCellValue("");
sheet.addMergedRegion(CellRangeAddress.valueOf("B6:B6"));
cell = row6.createCell(2);
cell.setCellValue((String) addrDetails.get("COMP_ADD_3"));
sheet.addMergedRegion(CellRangeAddress.valueOf("C6:G6"));
cell.setCellStyle(cellStyle);
}
rowNo++;
if (addrDetails.get("CONTACT") != null) {
XSSFRow row7 = sheet.createRow(rowNo);
XSSFCell cell = row7.createCell(1);
cell = row7.createCell(1);
cell.setCellStyle(cellStyle);
cell.setCellValue("Contact");
sheet.addMergedRegion(CellRangeAddress.valueOf("B7:B7"));
cell = row7.createCell(2);
cell.setCellValue((String) addrDetails.get("CONTACT"));
sheet.addMergedRegion(CellRangeAddress.valueOf("C7:G7"));
cell.setCellStyle(cellStyle);
}
rowNo++;
String pattern = "###,###.##";
DecimalFormat decimalFormat = new DecimalFormat(pattern);
// Row 8
XSSFRow row8 = sheet.createRow(rowNo);
XSSFCell cell = row8.createCell(1);
cell = row8.createCell(0);
cell.setCellStyle(cellStyle);
cell.setCellValue("Document No :");
cell = row8.createCell(1);
cell.setCellValue(fhdocNo);
cell.setCellStyle(cellStyle);
cell = row8.createCell(2);
cell.setCellStyle(cellStyle);
cell.setCellValue("From Date :");
cell = row8.createCell(3);
cell.setCellValue(fromDate);
cell.setCellStyle(cellStyle);
cell = row8.createCell(4);
cell.setCellStyle(cellStyle);
cell.setCellValue("To Date :");
cell = row8.createCell(5);
cell.setCellValue(toDate);
cell.setCellStyle(cellStyle);
cell = row8.createCell(6);
cell.setCellStyle(cellStyle);
cell.setCellValue("Period Type :");
cell = row8.createCell(7);
cell.setCellValue(period);
cell.setCellStyle(cellStyle);
rowNo++;
// Table Header
XSSFRow row9 = sheet.createRow(rowNo);
XSSFCell cell9 = row9.createCell(1);
XSSFCellStyle headerCellStyleAmount = xb.createCellStyle();
headerCellStyleAmount.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
XSSFFont minusIndicatorfont = xb.createFont();
minusIndicatorfont.setColor(new XSSFColor(Color.red));
headerCellStyleAmount.setFont(minusIndicatorfont);
XSSFRow xssfHeader = sheet.createRow(rowIdx);
XSSFColor color1 = new XSSFColor(Color.gray);
XSSFCellStyle headCellStyle;
headCellStyle = (XSSFCellStyle) cell9.getCellStyle();
headCellStyle.setFillBackgroundColor(new XSSFColor(new Color(216,
216, 216)));
cell9 = xssfHeader.createCell(1);
cell9.setCellStyle(cellStyle);
cell9.setCellValue("");
for (int i = 0; i < listSize; i++) {
XSSFCell xssfCell = xssfHeader.createCell(cellIdx++);
xssfCell.setCellValue(monthList.get(i).getSD_LABEL());
headCellStyle.setFillForegroundColor(color1);
headCellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
xssfCell.setCellStyle(headCellStyle);
}
rowIdx++;
xb.setSheetName(0, sheetName);
/*
* HttpServletResponse response = (HttpServletResponse)
* externalContext .getResponse(); OutputStream os =
* response.getOutputStream(); wb.write(os);
* response.setHeader("Content-Disposition",
* "attachment; filename=\"" + fileName + ".xls");
* response.getOutputStream().flush();
* response.getOutputStream().close();
* FacesContext.getCurrentInstance().responseComplete();
*/
ExternalContext externalContext = FacesContext.getCurrentInstance()
.getExternalContext();
writeExcelToResponse(externalContext, xb, fileName);
} catch (Exception e) {
e.printStackTrace();
}
If you use this snippet it will work:
XSSFCellStyle style = workbook.createCellStyle();
XSSFColor myColor = new XSSFColor(Color.RED);
style.setFillForegroundColor(myColor);
style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
I can give you this link where a description is given how to use XSSF.
The main change is to create a new XSSFCellStyle out of the Workbook and to set the fill-pattern.
Apache POI 4.0.0 answer. How to set background color of an Excel cell:
//create workbook/sheet/row/cell
IndexedColorMap colorMap = outputWorkbook.getStylesSource().getIndexedColors();
java.awt.Color pigeonBlue = new java.awt.Color(189, 215, 238);
XSSFColor myBackgroundColor = new XSSFColor(pigeonBlue, colorMap);
XSSFCellStyle myCellStyle = outputWorkbook.createCellStyle();
myCellStyle.setFillForegroundColor(myBackgroundColor);
myCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
outputCell.setCellStyle(myCellStyle);
outputCell.setCellValue("Hi There");
// write & close workbook
Your cell should look something like this:

Fill the cell in xls file, using apache-poi

Why it doesn't work? I use setFillForegroundColor and it clears the cell, rather than to fill it with a color(lime) .
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
CreationHelper createHelper = workbook.getCreationHelper();
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.LIME.getIndex());
......
label1:
for (int i=0;i<ListOfList.size();i++) {
Row row = sheet.getRow(i);
for (int j=0;j<ListOfList.get(i).size();j++) {
for (int k=0;k<List.size();k++){
if (List.get(k).equals(ListOfList.get(i).get(j)) | ListOfList.get(i).get(j).contains(List.get(k))) {
System.out.println("("+List.get(k)+") ASU <--> ("+ListOfList.get(i).get(j)+") RZS "+"Строчка: "+i+" Столбец: "+j);
row.createCell(2+j).setCellStyle(style);
}
else {}
}
}
}

Categories