Changing template when applying cell style in xls file using apache poi - java

I have a problem with HSSFWorkbook object. I have a XLS template, where row no 14 is light gray, and next rows are populated with bean values.
During generation of the report, I want to change the date style for which I am writing below code but it's changing the whole tempalate.
workbook = (HSSFWorkbook) WorkbookFactory.create(new FileInputStream(finalFilePath));
sheet = workbook.getSheetAt(0);
workbook.setActiveSheet(0);
CreationHelper creationHelper = workbook.getCreationHelper();
HSSFCellStyle importDataDateStyle = workbook.createCellStyle();
importDataDateStyle.setDataFormat(creationHelper.createDataFormat().getFormat("M/d/yyyy"));
BeanClass bean = new BeanClass();
if (bean.getLastDate() != null) {
migrationBeanRow.createCell(6).setCellValue(lastDate);
} else {
migrationBeanRow.createCell(6).setCellValue(notAvailable);
}
migrationBeanRow.getCell(6).setCellStyle(cellStyleDate);
workbook.write(fileOut);
workbook.close();
This code is working correctly for xlsx(XSSFWorkbook) using XSSFStyle format but changing template for when trying for xls(HSSFWorkbook) file.
Pleas find below template snippet before and after file generation.
pre code template
post code template(Date format is coming as expected but template header color is changing from gray to green)

Related

Can't export String as Hyperlink in .xlsx File - Java 8 & POI 3.17

I try to build an Excel file where the first cell is everytime a Hyperlink. I use Java 8 and POI 3.17 in a Spring Boot API. The excel export works fine, but the problem is, that the first cell is now complete empty. I don't get any warning or error or something else. The Problematic code:
final XSSFWorkbook wb = exportHelperService.loadWorkbookTemplate(path);
XSSFHyperlink url_link = wb.getCreationHelper().createHyperlink(HyperlinkType.URL) // definition for Hyperlink
fillWorkbook(....) { // here i gonna fill my workbook - everything works fine
url_link.setAddress("http://www.google.de/"); // definition of url address - checked that its not empty
exportHelperService.insertHyperlinkValue(url_link, "Cell_1", row); // calls function that writes into the cell 1 - for all other cells there is NO problem
// ... code that works fine ...
}
public void insertHyperlinkValue(XSSFHyperlink value, String columName, Row row) {
if (value != null) {
Cell cell = row.getCell(columnIndexMap.get(columName), CREATE_NULL_AS_BLANK);
cell.setHyperlink(value); // <--- HERE IS THE PROBLEM
}
}
I tested the insertHyperlinkValue() function to print only a string and it worked fine, but for a hyperlink it don't wanna work... Where is my false ? Thank you very much for each answer !!!
The cell already holds the link, it just has no text/style.
XSSFWorkbook wb = new XSSFWorkbook();
XSSFHyperlink link = wb.getCreationHelper().createHyperlink(HyperlinkType.URL);
XSSFCellStyle hlinkstyle = wb.createCellStyle();
XSSFFont hlinkfont = wb.createFont();
hlinkfont.setUnderline(XSSFFont.U_SINGLE);
hlinkfont.setColor(IndexedColors.BLUE.index);
hlinkstyle.setFont(hlinkfont);
link.setAddress("http://www.google.de/");
Sheet s = wb.createSheet();
Row r = s.createRow(0);
Cell c = r.createCell(0);
c.setHyperlink(link);
c.setCellStyle(hlinkstyle); //<-- make it look like link
c.setCellValue(link.getAddress()); // <-- important
wb.write(new FileOutputStream(new File("D:\\Test\\hyperlink.xlsx")));
wb.close();
You just need to set the cell text and style and you are good to go.

Can't see styling changes in POI Apache Excel .xls document

I wonder how to autoSize the columns in Excel doc.
When I run this code it don't do a jack shit in the document. And I can't really find out what is wrong!
Literally, nothing is autoSized in the document. I don't understand what could be wrong!! Very frustrating problem..
Also, I would be happy to get some feedback on the code, do I practice bad coding habits?
Thanks!
Here is my code:
try
{
FileInputStream myxls = new FileInputStream("/Users/xxxxxx/Desktop/tryIt.xls");
HSSFWorkbook workbook = new HSSFWorkbook(myxls);
HSSFSheet sheet = workbook.getSheetAt(0);
int lastRow=sheet.getLastRowNum();
HSSFCellStyle styleRowHeading = workbook.createCellStyle();
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont fontRowHeading = workbook.createFont();
HSSFFont font = workbook.createFont();
fontRowHeading.setBold(true);
fontRowHeading.setFontName(HSSFFont.FONT_ARIAL);
fontRowHeading.setFontHeightInPoints((short) 14);
styleRowHeading.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
styleRowHeading.setFillPattern(FillPatternType.SOLID_FOREGROUND);
styleRowHeading.setBorderTop(BorderStyle.MEDIUM);
styleRowHeading.setBorderBottom(BorderStyle.MEDIUM);
styleRowHeading.setBorderLeft(BorderStyle.MEDIUM);
styleRowHeading.setBorderRight(BorderStyle.MEDIUM);
styleRowHeading.setFont(fontRowHeading);
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)12);
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setBorderTop(BorderStyle.MEDIUM);
style.setBorderBottom(BorderStyle.MEDIUM);
style.setBorderLeft(BorderStyle.MEDIUM);
style.setBorderRight(BorderStyle.MEDIUM);
style.setFont(font);
// Create heading
if(lastRow <=0){
Row rowHeading = sheet.createRow(lastRow);
rowHeading.createCell(0).setCellValue("TEST1");
rowHeading.createCell(1).setCellValue("TEST2");
rowHeading.createCell(2).setCellValue("TEST3");
rowHeading.createCell(3).setCellValue("TEST4");
for(int i = 0; i < 4; i++){
rowHeading.getCell(i).setCellStyle(styleRowHeading);
}
}
Row row = sheet.createRow(++lastRow);
int i = 0;
org.apache.poi.ss.usermodel.Cell cellId = row.createCell(i);
org.apache.poi.ss.usermodel.Cell cellId1 = row.createCell(i+=1);
org.apache.poi.ss.usermodel.Cell cellId2 = row.createCell(i+=1);
org.apache.poi.ss.usermodel.Cell cellId3 = row.createCell(i+=1);
cellId.setCellValue(todaysDate);
cellId1.setCellValue(txt_year.getText());
cellId2.setCellValue(txt_correct.getText());
cellId3.setCellValue(txt_errors.getText());
cellId.setCellStyle(style);
cellId1.setCellStyle(style);
cellId2.setCellStyle(style);
cellId3.setCellStyle(style);
// Autofit
for(int w = 0; w < 5; w++){
sheet.autoSizeColumn(w);
}
myxls.close();
FileOutputStream output_file =new FileOutputStream(new File("/Users/xxxx/Desktop/tryIt.xls"));
//write changes
workbook.write(output_file);
output_file.close();
System.out.println("SUCCESSSSSSSSS!");
}catch(Exception e){
System.out.println(e.getMessage());
}
I assume HSSFCellStyle might be causing issues here, could you change to CellStyle and check once if you see any formatting changes:
CellStyle style=null;
XSSFFont defaultFont= wb.createFont();
defaultFont.setFontHeightInPoints((short)10);
defaultFont.setFontName("Arial");
defaultFont.setColor(IndexedColors.BLACK.getIndex());
defaultFont.setBold(false);
defaultFont.setItalic(false);
XSSFFont font= wb.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("Arial");
font.setColor(IndexedColors.WHITE.getIndex());
font.setBold(true);
font.setItalic(false);
style=row.getRowStyle();
style.setFillBackgroundColor(IndexedColors.DARK_BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFont(font);
Key things to keep in mind:
Let's understand the basic difference between HSSFWorkbook and XSSFWorkbook
HSSFWorkbook: This class has methods to read and write Microsoft Excel files in .xls format.
XSSFWorkbook: This class has methods to read and write Microsoft Excel and OpenOffice xml files in .xls or .xlsx format.
SXSSF: it is an API-compatible streaming extension of XSSF to be used when very large spreadsheets have to be produced, and heap space is limited
Workbook
This is the super-interface of all classes that create or maintain
Excel workbooks. It belongs to the org.apache.poi.ss.usermodel package
and both the above mentioned XSSF, HSSF and SXSSF are implementations of
WORKBOOK
Hence, my suggestion would be to until-unless utmost necessary, i.e, you need a specific feature for xlsx or xls, just go with the workbook implementation
Most of the styling changes are hit and trial. You need to keep
digging iterating with to finally find what you need.
Suggestions:
If you code for just HSSF via HSSFWorkbook, you can only work with .xls files. I'd suggest you go for the common ones wherever possible (workbook)
Your loading code should be something like:
Workbook wb = WorkbookFactory.create(new File("test.xls"));
Sheet s = wb.getSheetAt(0);
....
Now, it will auto-detect the type of the file and give you back a working object for either .xls or .xlsx based on what it finds. Also, wherever possible try to keep the styling and designing parts generic and version independent. That way the same code could be re-used for both formats.
If you need to have any specific feature which require either XSSF
or HSSF and can't use just the Workbook then do a check for the
type first like this:
Workbook wb = WorkbookFactory.create(myExcelFile);
Then you can check the exact type created by the factory:
if (wb instanceof HSSFWorkbook) {
// do whatever
} else if (wb instanceof SXSSFWorkbook) {
// do whatever
} else if (wb instanceof XSSFWorkbook) {
// do whatever
}

After updating existing cell value in .xlsx file using POI, the file is giving HTTP 403 if used by an API

I have an excel file which contains many columns and one set of data row in it.
After changing the value of the asOf field, as I am using it in API which is taking excel file, gives 403 Forbidden error. I have checked the following things:
The field is updated correctly. (I checked the formatting and cell style of excel after updating it manually.)
If I change the cell value manually then API is giving 200.
Image For Failure Response: When asOf field updated by Java Code
Image For Pass Response: When asOf field updated manually.
The image of field which I am updating is below:
Below is the java code that I am using:
public static void excelFileReadAndUpdate() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("./src/test/resources/testdata/HoldingDataWeekendDate.xlsx"));
FileOutputStream fileOut = new FileOutputStream("./src/test/resources/testdata/HoldingDataWeekendDate.xlsx");
XSSFSheet sheet1 = wb.getSheetAt(0);
XSSFRow row = sheet1.getRow(1);
XSSFCell cell = row.getCell(0);
cell.setCellValue("2018-10-31");
wb.write(fileOut);
fileOut.close();
}
Note: I tried other approaches also like using the workbook and preserve the formatting but it is not working. If I update the field manually after opening the excel then it works.
Any suggestion/advice would be great help.
Thanks in advance.
After searching and applying many approaches, finally, it has been resolved by applying some code giving read/write permission to that folder/file in java.
public static void excelFileReadAndUpdate() throws IOException {
final File file = new File("location of your excel file directory");
file.setReadable(true, false);
file.setExecutable(true, false);
file.setWritable(true, false);
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("./src/test/resources/testdata/HoldingDataWeekendDate.xlsx"));
FileOutputStream fileOut = new FileOutputStream("./src/test/resources/testdata/HoldingDataWeekendDate.xlsx");
XSSFSheet sheet1 = wb.getSheetAt(0);
XSSFRow row = sheet1.getRow(1);
XSSFCell cell = row.getCell(0);
cell.setCellValue("2018-10-31");
wb.write(fileOut);
fileOut.close();
}

Java Apache POI Excel set border on specific cell and set currency cell format

I am working to generate excel using java apache poi
i just need to beautify it (with border)
below is the excel that i have successfuly create
and here is the excel that i wanted (see those border and currency and background color)
heres some of my code to generate the excel
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("sheet1");
Row row = sheet.createRow(rowIndex);
row.createCell(0).setCellValue("Product Name");
row.createCell(1).setCellValue("name");
FileOutputStream fileOut = new FileOutputStream("excel.xlsx");
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
I assume you'd need to break down the creation of your cell in this format first before applying any style onto it:
Cell cell1 = row.createCell(0);
cell1.setCellValue("Product Name");
Later,
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setBorderTop((short) 1); // single line border
cellStyle.setBorderBottom((short) 1); // single line border
...//add many others here
cell1.setCellStyle(cellStyle); //apply that style to the cell
Simple way is to create a cellStyle at first and then just go ahead with numerous cell creations as per the application requirement! Next, just loop into each cell to apply the cellStyle if it is a common behavior that you need for all.
Hope that helps!

Lock single column in Excel using Apache POI

I want to create a Excel in which only a specific column is locked(Read-only), and the rest are editable,
I am using the following approach, but that doesn't seem to work.
Create two CellStyles, one with setLocked(true) and other with setLocked(false).
Then apply the locked style for all the cells in the column which needs to be locked, and the unlocked style for all the other cells.
Protect the sheet using sheet.protectSheet("");
But when I open the created Excel in open office, I notice that all the cells are locked!
None of them are editable.
How can I achieve the above requirement?
P.S : I cant use the data validation approach.
If you do the opposite it works. Protect the whole sheet and call setLocked(false) for the cells which should be editable.
String file = "c:\\poitest.xlsx";
FileOutputStream outputStream = new FileOutputStream(file);
Workbook wb = new XSSFWorkbook();
CellStyle unlockedCellStyle = wb.createCellStyle();
unlockedCellStyle.setLocked(false);
Sheet sheet = wb.createSheet();
sheet.protectSheet("password");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("TEST");
cell.setCellStyle(unlockedCellStyle);
wb.write(outputStream);
outputStream.close();

Categories

Resources