CellStyle dataformat for XLSX - java

I have some code like :
CellStyle cs2 = wb.createCellStyle();
CellStyle cs4 = wb.createCellStyle();
cs4.setDataFormat(HSSFDataFormat.getBuiltinFormat("CELL_TYPE_NUMERIC"));
cs2.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
this is for creating xls reports. How do i change this code to create XLSX reports ?
will the following work ?
XSSFDataFormat format = (XSSFDataFormat) wb.createDataFormat();
cs2.setDataFormat(format.getFormat("text"));
Please help.
Thanks

Yes, built-in formats will still work with .xlsx spreadsheets in Apache POI.
Even if the Javadocs for XSSFDataFormat#getFormat(String) don't mention it, the source code tells all:
public short getFormat(String format) {
int idx = BuiltinFormats.getBuiltinFormat(format);
if(idx == -1) idx = stylesSource.putNumberFormat(format);
return (short)idx;
}
It will look up the data format in the BuiltinFormats object first, and if not found, it will create a new one.
I've tested this on creating a .xlsx spreadsheet, and using "text" works. I created numeric cells, and I set those cells to a CellStyle with a XSSFDataFormat created with "text", and the cells are "text"-styled in the resultant spreadsheet.

Related

Apache POI Data Formatter unable to apply custom format "0.0 p.p.;(0.0 p.p.)"

In my Excel file that I am trying to convert using Apache POI, I have a cell that has numeric value as -3.97819466831428 and Custom format as "0.0 p.p.;(0.0 p.p.)". So, in Excel the value that is displayed is "(4.0 p.p.)"
When I convert the same using POI library, I get the output as: "(4.0 p"
How can I get the same value as in Excel: (4.0 p.p.) ?
The way I am using DataFormatter is:
val = dataFormatter.formatRawCellContents(cell.getNumericCellValue(), style.getDataFormat(), style.getDataFormatString());
I believe the problem is coming from the usage of "p.p." in the data format string, especially the dots. When I print the data format string from POI using style.getDataFormatString(), I get the format as "0.0\ \p.\p.;(0.0\ \p.\p.\)".
Even if I manually change the format string to use "0.0;(0.0\ \p\.\p\.\)", still its the same result. So, I am out of ideas now. How can I get the full result back from data-formatter like in Excel as "(4.0 p.p.)" ?
Another question that I have is: Is it possible using Apache POI to get the actual displayed value in Excel file? Like in this case, is it possible to get the value "(4.0 p.p.)" directly from Excel without having to apply any data formatting in POI?
This is an error in apache poi's DataFormatter while translating the Excel number format 0.0\ \p.\p.;\(0.0\ \p.\p.\) into a java.text.Format. The correct corresponding java.text.Format would be a new java.text.DecimalFormat("0.0' p.p.';(0.0' p.p.')"). But apache poi's DataFormatter fails to translate this properly.
You should file a bug report to apache poi about this. In that bug report you should provide a working example (full Java code and a sample Excel file) to reproduce the issue.
As a workaround one can tell DataFormatter how single special Excel number formats shall be translated. For this use the method DataFormatter.addFormat.
Example:
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
class DataFormatterAddFormat {
public static void main(String[] args) throws Exception {
Workbook workbook = WorkbookFactory.create(new FileInputStream("ExcelExample.xlsx"));
DataFormatter dataFormatter = new DataFormatter();
FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
dataFormatter.addFormat("0.0 p.p.;(0.0 p.p.)",
new java.text.DecimalFormat("0.0' p.p.';(0.0' p.p.')"));
dataFormatter.addFormat("0.0\" p.p.\";\\(0.0\" p.p.\"\\)",
new java.text.DecimalFormat("0.0' p.p.';(0.0' p.p.')"));
dataFormatter.addFormat("0.0\\ \\p.\\p.;\\(0.0\\ \\p.\\p.\\)",
new java.text.DecimalFormat("0.0' p.p.';(0.0' p.p.')"));
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
String value = dataFormatter.formatCellValue(cell, formulaEvaluator);
System.out.println(value);
}
}
workbook.close();
}
}
This is now able correct translating the added special number formats. Of course this is not really the final solution since the need here is to catch all possible Excel formats which have to be translated. That's why the hint to file a bug report to apache poi.
Btw.: The Excel format 0.0" p.p.";\(0.0" p.p."\) would be more general for this. It avoids confusing the dot (.) in p.p. with the decimal separator.
To your question about getting the formatted value directly from the Excel file: This is not possible. All Excel versions store values and styles separate. Numeric values are always stored as floating point values in double precision. Number formats for those values are stored in a separate styles section of the file. So best practice to get cell values styled as in Excel using apache poi is using DataFormatter.formatCellValue as shown in my code sample.

How to change the cellType from custom to Text in POI

I am trying to parse an excel file which is having some columns which are in Custom format.I have to convert them into Text before parsing.I am trying to implement a condition that if the celltype is blank and custom it will be converted to text format ,
I am trying this code but not working
Workbook workbook = excelManager.getWorkbook();
DataFormat fmt = workbook.createDataFormat();
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(fmt.getFormat("#"));
But I think this # will not work for all custom cells. Can anyone please help me? I am using poi 3.16 and version can not be changed.

POI: Format integer in Excelsheet

I have a List of integers, that i want to export to Excel. But everytime the value is shown with decimal positions:
worksheet.getRow(0).getCell(1).setCellType(Cell.CELL_TYPE_NUMERIC);
worksheet.getRow(0).getCell(1).setCellValue(2); // Excel shows here 2.00
After that I've tried it with an custom style:
CellStyle numericStyle = workbook.createCellStyle();
numericStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("#"));
worksheet.getRow(0).getCell(1).setCellValue(Double.parseDouble(2));
worksheet.getRow(0).getCell(1).setCellStyle(numericStyle);
Now it seem to be correct formated in Excel, but Excel (2013) says, the file is unsafe and should not be edited.
How is the correct way to format an integer-cell with poi?
Thanks for your help.
Try with:
// at the beggining, create one style that would be applied for all Integers
CellStyle integerStyle = workbook.createCellStyle();
integerStyle.setDataFormat(0);
// use style wherever you need it
worksheet.getRow(0).getCell(1).setCellValue(Integer.valueOf(2));
worksheet.getRow(0).getCell(1).setCellStyle(integerStyle);
numericStyle.setDataFormat(workbook.createDataFormat().getFormat("#,##0"));
where workbook is your HSSFWorkbook

Apache POI - Show a numberic data starting with 0

I am creating an excel using Apache POI class. I have a column with data as 07898.
When I opened the excel the data is showing properly with 07898 with a warning message. When I click the mouse inside the excel is considering it as number and removing the 0 automatically.
But if I change the column type as text in Microsoft excel, it is not removing the 0. But I am not able to set the column type as Text. It is always Generic.
Any suggestion please let me know. Thank you.
I am setting the type as String, but it is not working properly.
SXSSFWorkbook hwb = new SXSSFWorkbook(100);
Sheet sheet = hwb.createSheet(strReportName);
Cell excelheadercell = excelheader.createCell((short) icolumns);
excelheadercell.setCellValue("07898");
CellStyle cellstyle = hwb.createCellStyle();
Font font = hwb.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
cellstyle.setFont(font);
excelheadercell.setCellStyle(cellstyle);
**excelheadercell.setCellType(Cell.CELL_TYPE_STRING);**

single cell read only in excel using java

How can I make read only cell in Excel using Java ?
You may use Apache POI library to achieve this. Here is a simple code sample:
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Test");
Row row = sheet.createRow(0);
CellStyle style = wb.createCellStyle();
style.setLocked(true);
cell = row.createCell(0);
cell.setCellStyle(style);
// this is important as locking is pnly activated if sheet is protected
sheet.protectSheet("");
Maybe you can try jExcel. It is quite simple and easy to use.
Take a look at the Apache POI project, specifically the HSSF & XSSF subprojects, that provides a Java library to manipulate Excel documents.

Categories

Resources