Could you please suggest on next case?
I`ve set up dataformat and cell type ("#,###.00", NUMERIC)
(I want thounsand separator plus two decimal numbers)
It works as I expected but to have formatted cells I need to select them first
Before selection data looks not formatted
In other words I have to select cell so that it is formatted, otherwise it stays without any formatting
CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.RIGHT);
style.setLocked(locked);
style.setDataFormat(workbook.createDataFormat().getFormat("#,###.00"));
cell.setCellStyle(style);
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(<big decimal value>.toString());
Simply do not set cell value as string if you need a numeric cell value. If you set cell value as String, then the cell type also will be string. This is independent of setting CellType before setting cell value. While setting a String cell value the type changes to string always.
See API documentation which shows that Cell.setCellType is deprecated and what Cell.setCellValue methods are possible.
You needs setting a double cell value if cell shall have numeric content.
Example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.math.BigDecimal;
import java.util.Random;
class CreateExcelCellNumberFormat {
public static void main(String[] args) throws Exception {
try (Workbook workbook = new XSSFWorkbook();
FileOutputStream fileout = new FileOutputStream("Excel.xlsx") ) {
CellStyle style = workbook.createCellStyle();
style.setDataFormat(workbook.createDataFormat().getFormat("#,###.00"));
Sheet sheet = workbook.createSheet();
for (int r = 0; r < 10; r++) {
Cell cell = sheet.createRow(r).createCell(0);
cell.setCellStyle(style);
BigDecimal bigDecimal = new BigDecimal(new Random().nextDouble() * 10000000000000d);
cell.setCellValue(bigDecimal.doubleValue());
}
sheet.setColumnWidth(0, 25 * 256);
workbook.write(fileout);
}
}
}
Related
I am creating excel sheet using apache poi. I have numbers like - 337499.939437217, which I want to show as it is in excel without rounding off. Also the cell format should be number (for some columns) and currency (for some columns).
Please suggest which BuiltinFormats should I use to achieve this.
Many thanks for the help.
At first you need to know how to use DataFormats. Then you need to know the guidelines for customizing a number format.
For your number -337499.939437217 which will be displayed rounded with general number format, you could use format #.###############. The # means a digit which will be displayed only if needed (is not leading zero and/or is not zero as last decimal digit) - see guidelines. So the whole format means show up to 15 decimal digits if needed but only as much as needed.
For currency you should really using a built in number format for currency. So the currency symbol depends on the locale settings of Excel. The following BuiltinFormats are usable with apache poi. Using a built in number format you need only the hexadecimal format numbers.
Example:
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CreateNumberFormats {
public static void main(String[] args) throws Exception {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("format sheet");
CellStyle style;
DataFormat format = wb.createDataFormat();
Row row;
Cell cell;
short rowNum = 0;
short colNum = 0;
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(-337499.939437217); // general format
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("#.###############")); // custom number format
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(-337499.939437217);
cell.setCellStyle(style);
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(123.456789012345);
cell.setCellStyle(style);
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(123456789.012345);
cell.setCellStyle(style);
style = wb.createCellStyle();
style.setDataFormat((short)0x7); // builtin currency format
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(-1234.5678);
cell.setCellStyle(style);
sheet.autoSizeColumn(0);
FileOutputStream fileOut = new FileOutputStream("CreateNumberFormats.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}
I am using Apache POI API to getting values from an Excel file.
Everything is working great except with cells containing formulas. In fact, the cell.getStringCellValue() is returning the formula used in the cell and not the value of the cell.
I tried to use evaluateFormulaCell() method but it's not working because I am using GETPIVOTDATA Excel formula and this formula is not implemented in the API:
Exception in thread "main" org.apache.poi.ss.formula.eval.NotImplementedException: Error evaluating cell Landscape!K11
at org.apache.poi.ss.formula.WorkbookEvaluator.addExceptionInfo(WorkbookEvaluator.java:321)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:288)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluate(WorkbookEvaluator.java:221)
at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateFormulaCellValue(HSSFFormulaEvaluator.java:320)
at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateFormulaCell(HSSFFormulaEvaluator.java:213)
at fromExcelToJava.ExcelSheetReader.unAutreTest(ExcelSheetReader.java:193)
at fromExcelToJava.ExcelSheetReader.main(ExcelSheetReader.java:224)
Caused by: org.apache.poi.ss.formula.eval.NotImplementedException: GETPIVOTDATA
at org.apache.poi.hssf.record.formula.functions.NotImplementedFunction.evaluate(NotImplementedFunction.java:42)
For formula cells, excel stores two things. One is the Formula itself, the other is the "cached" value (the last value that the forumla was evaluated as)
If you want to get the last cached value (which may no longer be correct, but as long as Excel saved the file and you haven't changed it it should be), you'll want something like:
for(Cell cell : row) {
if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
System.out.println("Formula is " + cell.getCellFormula());
switch(cell.getCachedFormulaResultType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.println("Last evaluated as: " + cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
break;
}
}
}
Previously posted solutions did not work for me. cell.getRawValue() returned the same formula as stated in the cell. The following function worked for me:
public void readFormula() throws IOException {
FileInputStream fis = new FileInputStream("Path of your file");
Workbook wb = new XSSFWorkbook(fis);
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
CellReference cellReference = new CellReference("C2"); // pass the cell which contains the formula
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
CellValue cellValue = evaluator.evaluate(cell);
switch (cellValue.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cellValue.getBooleanValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cellValue.getNumberValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cellValue.getStringValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
break;
// CELL_TYPE_FORMULA will never happen
case Cell.CELL_TYPE_FORMULA:
break;
}
}
There is an alternative command where you can get the raw value of a cell where formula is put on. It's returns type is String. Use:
cell.getRawValue();
If the need is to read values from Excel sheets and having them as strings then, for example to present them somewhere or to use them in text file formats, then using DataFormatter will be the best.
DataFormatter is able to get a string from each cell value, whether the cell value itself is string, boolean, number, error or date. This string then looks the same as Excel will show it in the cells in it's GUI.
Only problem are formula cells. Up to apache poi 5.1.0 a FormulaEvaluator is needed to evaluate the formulas while using DataFormatter. This fails when apache poi is not able evaluating the formula. From 5.2.0 on the DataFormatter can be set to use cached values for formula cells. Then no formula evaluation is needed if Excel had evaluated the formulas before.
Complete example:
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
class ReadExcel {
public static void main(String[] args) throws Exception {
Workbook workbook = WorkbookFactory.create(new FileInputStream("./ExcelExample.xlsx"));
// up to apache poi 5.1.0 a FormulaEvaluator is needed to evaluate the formulas while using DataFormatter
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
DataFormatter dataFormatter = new DataFormatter(new java.util.Locale("en", "US"));
// from 5.2.0 on the DataFormatter can set to use cached values for formula cells
dataFormatter.setUseCachedValuesForFormulaCells(true);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
//String value = dataFormatter.formatCellValue(cell, evaluator); // up to apache poi 5.1.0
String value = dataFormatter.formatCellValue(cell); // from apache poi 5.2.0 on
System.out.println(value);
}
}
workbook.close();
}
}
If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:
CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);
At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345") instead of a fractional value (e.g. "12345.0"). Note that setCellType is available in interface Cell(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase. Obviously, it would be nicer either to have getRawValue in the Cell interface or at least to be able use getStringCellValue on non STRING cell types. Unfortunately, all replacements of setCellType mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).
SelThroughJava's answer was very helpful I had to modify a bit to my code to be worked .
I used https://mvnrepository.com/artifact/org.apache.poi/poi and https://mvnrepository.com/artifact/org.testng/testng as dependencies .
Full code is given below with exact imports.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelFormulaValue {
private static final CellType NUMERIC = null;
public static void main(String[] args) {
try {
readFormula();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void readFormula() throws IOException {
FileInputStream fis = new FileInputStream("C:eclipse-workspace\\sam-webdbriver-diaries\\resources\\tUser_WS.xls");
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(fis);
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
CellReference cellReference = new CellReference("G2"); // pass the cell which contains the formula
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
CellValue cellValue = evaluator.evaluate(cell);
System.out.println("Cell type month is "+cellValue.getCellTypeEnum());
System.out.println("getNumberValue month is "+cellValue.getNumberValue());
// System.out.println("getStringValue "+cellValue.getStringValue());
cellReference = new CellReference("H2"); // pass the cell which contains the formula
row = sheet.getRow(cellReference.getRow());
cell = row.getCell(cellReference.getCol());
cellValue = evaluator.evaluate(cell);
System.out.println("getNumberValue DAY is "+cellValue.getNumberValue());
}
}
I'm trying to copy from cells from one workbook to another with the latest version of Apache POI (4.1.2).
If both workbooks are .xlsx files, everything works fine. But if the source workbook is an (old) .xls file and the destination workbook is an .xlsx file, the following code fails
// Copy style from old cell and apply to new cell
CellStyle newCellStyle = targetWorkbook.createCellStyle();
newCellStyle.cloneStyleFrom(sourceCell.getCellStyle());
targetCell.setCellStyle(newCellStyle);
The exception that's thrown is:
java.lang.IllegalArgumentException: Can only clone from one XSSFCellStyle to another, not between HSSFCellStyle and XSSFCellStyle
If we can't use cloneStyleFrom when the files (or Workbook objects) are of different types, how can we convert a HSSFCellStyle object to a XSSFCellStyle?
The answer to your question "How can we convert a HSSFCellStyle object to a XSSFCellStyle?" is: We can't do that using apache poi 4.1.2. This simply is not supported as clearly stated in CellStyle.cloneStyleFrom: "However, both of the CellStyles will need to be of the same type (HSSFCellStyle or XSSFCellStyle)."
The other question is: Should we at all convert one cell style into another? Or what use cases are there for CellStyle.cloneStyleFrom at all? In my opinion there are none. There are Excel limitations for the count of unique cell formats/cell styles. See Excel specifications and limits. So we should not create a single cell style for each single cell because then those limitations will be reached very fast. So instead of cloning cell styles we should get the style properties from source style style1 and then using CellUtil.setCellStyleProperties to set those style properties to the other cell in question. This method attempts to find an existing CellStyle that matches the cell's current style plus styles properties in properties. A new style only is created if the workbook does not contain a matching style.
Since your question title is "Copy cells between Excel workbooks with Apache POI", I have created a working draft of how I woud do this.
The following code first gets a existent Workbook.xls as HSSFWorkbook wb1 and creates a new XSSFWorkbook wb2. Then it loops over all cells of the first sheet of wb1 and tries copying those cells into the first sheet of wb2. To do so there is a method copyCells(Cell cell1, Cell cell2) which uses copyStyles(Cell cell1, Cell cell2). The latter gets the style properties from source style style1 got from cell1 and then uses CellUtil.setCellStyleProperties to set those style properties to cell2. For copying fonts copyFont(Font font1, Workbook wb2) is used. This tries creating new fonts in wb2 only if such a font is not already present in that workbook. This is necessary because there also is a limit of unique font types per workbook in Excel.
Working example:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.util.CellUtil;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;
class ExcelCopyCells {
static Font copyFont(Font font1, Workbook wb2) {
boolean isBold = font1.getBold();
short color = font1.getColor();
short fontHeight = font1.getFontHeight();
String fontName = font1.getFontName();
boolean isItalic = font1.getItalic();
boolean isStrikeout = font1.getStrikeout();
short typeOffset = font1.getTypeOffset();
byte underline = font1.getUnderline();
Font font2 = wb2.findFont(isBold, color, fontHeight, fontName, isItalic, isStrikeout, typeOffset, underline);
if (font2 == null) {
font2 = wb2.createFont();
font2.setBold(isBold);
font2.setColor(color);
font2.setFontHeight(fontHeight);
font2.setFontName(fontName);
font2.setItalic(isItalic);
font2.setStrikeout(isStrikeout);
font2.setTypeOffset(typeOffset);
font2.setUnderline(underline);
}
return font2;
}
static void copyStyles(Cell cell1, Cell cell2) {
CellStyle style1 = cell1.getCellStyle();
Map<String, Object> properties = new HashMap<String, Object>();
//CellUtil.DATA_FORMAT
short dataFormat1 = style1.getDataFormat();
if (BuiltinFormats.getBuiltinFormat(dataFormat1) == null) {
String formatString1 = style1.getDataFormatString();
DataFormat format2 = cell2.getSheet().getWorkbook().createDataFormat();
dataFormat1 = format2.getFormat(formatString1);
}
properties.put(CellUtil.DATA_FORMAT, dataFormat1);
//CellUtil.FILL_PATTERN
//CellUtil.FILL_FOREGROUND_COLOR
FillPatternType fillPattern = style1.getFillPattern();
short fillForegroundColor = style1.getFillForegroundColor(); //gets only indexed colors, no custom HSSF or XSSF colors
properties.put(CellUtil.FILL_PATTERN, fillPattern);
properties.put(CellUtil.FILL_FOREGROUND_COLOR, fillForegroundColor);
//CellUtil.FONT
Font font1 = cell1.getSheet().getWorkbook().getFontAt(style1.getFontIndexAsInt());
Font font2 = copyFont(font1, cell2.getSheet().getWorkbook());
properties.put(CellUtil.FONT, font2.getIndexAsInt());
//BORDERS
BorderStyle borderStyle = null;
short borderColor = -1;
//CellUtil.BORDER_LEFT
//CellUtil.LEFT_BORDER_COLOR
borderStyle = style1.getBorderLeft();
properties.put(CellUtil.BORDER_LEFT, borderStyle);
borderColor = style1.getLeftBorderColor();
properties.put(CellUtil.LEFT_BORDER_COLOR, borderColor);
//CellUtil.BORDER_RIGHT
//CellUtil.RIGHT_BORDER_COLOR
borderStyle = style1.getBorderRight();
properties.put(CellUtil.BORDER_RIGHT, borderStyle);
borderColor = style1.getRightBorderColor();
properties.put(CellUtil.RIGHT_BORDER_COLOR, borderColor);
//CellUtil.BORDER_TOP
//CellUtil.TOP_BORDER_COLOR
borderStyle = style1.getBorderTop();
properties.put(CellUtil.BORDER_TOP, borderStyle);
borderColor = style1.getTopBorderColor();
properties.put(CellUtil.TOP_BORDER_COLOR, borderColor);
//CellUtil.BORDER_BOTTOM
//CellUtil.BOTTOM_BORDER_COLOR
borderStyle = style1.getBorderBottom();
properties.put(CellUtil.BORDER_BOTTOM, borderStyle);
borderColor = style1.getBottomBorderColor();
properties.put(CellUtil.BOTTOM_BORDER_COLOR, borderColor);
CellUtil.setCellStyleProperties(cell2, properties);
}
static void copyCells(Cell cell1, Cell cell2) {
switch (cell1.getCellType()) {
case STRING:
/*
//TODO: copy HSSFRichTextString to XSSFRichTextString
RichTextString rtString1 = cell1.getRichStringCellValue();
cell2.setCellValue(rtString1); // this fails if cell2 is XSSF and rtString1 is HSSF
*/
String string1 = cell1.getStringCellValue();
cell2.setCellValue(string1);
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell1)) {
Date date1 = cell1.getDateCellValue();
cell2.setCellValue(date1);
} else {
double cellValue1 = cell1.getNumericCellValue();
cell2.setCellValue(cellValue1);
}
break;
case FORMULA:
String formula1 = cell1.getCellFormula();
cell2.setCellFormula(formula1);
break;
//case : //TODO: further cell types
}
copyStyles(cell1, cell2);
}
public static void main(String[] args) throws Exception {
Workbook wb1 = WorkbookFactory.create(new FileInputStream("Workbook.xls"));
Workbook wb2 = new XSSFWorkbook();
Sheet sheet1 = wb1.getSheetAt(0);
Sheet sheet2 = wb2.createSheet();
Set<Integer> columns = new HashSet<Integer>();
Row row2 = null;
Cell cell2 = null;
for (Row row1 : sheet1) {
row2 = sheet2.createRow(row1.getRowNum());
for (Cell cell1 : row1) {
columns.add(cell1.getColumnIndex());
cell2 = row2.createCell(cell1.getColumnIndex());
copyCells(cell1, cell2);
}
}
wb1.close();
for (Integer column : columns) {
sheet2.autoSizeColumn(column);
}
FileOutputStream out = new FileOutputStream("Workbook.xlsx");
wb2.write(out);
out.close();
wb2.close();
}
}
If Workbook.xls looks like this:
then the resulting Workbook.xlsx looks like this:
Note: This is a working draft and needs to be completed. See TODO comments in the code. RichTextString cell values needs to be considered. Further cell types needs to be considered.
Method copyStyles only provides copying data format, fill pattern and fill foreground color (only for indexed colors), font and borders. Further cell style properties needs to be considered.
I am exporting data using Apache POI and the data has both Indian and US currency to be displayed..but after applying separate DataFormats too I get the same format(Indian INR) applied to all data's.
public static void main(String[] args) {
try {
System.out.println("*******Export Excel*********");
File myFile = new File("MyFirstExcel.xls");
FileOutputStream out = new FileOutputStream(myFile);
XSSFWorkbook xssfworkbook = new XSSFWorkbook();
XSSFSheet sheet = xssfworkbook.createSheet("new sheet");
XSSFCellStyle INRformatStyle = xssfworkbook.createCellStyle();
XSSFCellStyle USformatStyle = xssfworkbook.createCellStyle();
XSSFDataFormat df = xssfworkbook.createDataFormat();
USformatStyle.setDataFormat(df.getFormat("[$$-409]#,##0.00;"));
INRformatStyle.setDataFormat(df.getFormat("₹#,##0.00;"));
sheet.setColumnWidth(0, 7000);
XSSFRow row = sheet.createRow((short) 0);
XSSFCell cell = row.createCell((short) 0);
cell.setCellValue(100000.0);
cell.setCellStyle(USformatStyle);
XSSFRow row1 = sheet.createRow((short) 1);
XSSFCell cell1 = row1.createCell((short) 0);
cell1.setCellValue(100000.0);
cell1.setCellStyle(INRformatStyle);
xssfworkbook.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Expected $100,000.00
₹1,00,000.00
Actual $1,00,000.00
₹1,00,000.00
How the digit grouping is done in Excel is determined on the Windows system regional settings: Change the Windows regional settings. There is actually not a native option to set this via number format. So as long your system tells Excel: "We wants using format Hindi(India)" and so the digit grouping is set to 12,34,56,789 then this will be so for each number having thousands separator set.
Only possibility avoiding this is to set used system regional settings not to format Hindi(India) and so to set digit grouping not to 12,34,56,789.
Or using kind of fake number format as [$$-409]#\,###\,##0.00.
...
USformatStyle.setDataFormat(df.getFormat("[$$-409]#\\,###\\,##0.00"));
...
This is not using comma as thousands separator but , as text within the digits flow. So system's digit grouping is bypassed.
Complete example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
class CreateExcelDigitGroupings {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
DataFormat dataformat = workbook.createDataFormat();
CellStyle defaultCurrency = workbook.createCellStyle();
defaultCurrency.setDataFormat((short)8); //see https://poi.apache.org/apidocs/dev/org/apache/poi/ss/usermodel/BuiltinFormats.html
CellStyle defaultUSDCurrency = workbook.createCellStyle();
defaultUSDCurrency.setDataFormat(dataformat.getFormat("[$$-409]#,##0.00"));
CellStyle fakeHindiCurrency = workbook.createCellStyle();
fakeHindiCurrency.setDataFormat(dataformat.getFormat("₹#\\,##\\,##\\,##0.00"));
CellStyle fakeUSDCurrency = workbook.createCellStyle();
fakeUSDCurrency.setDataFormat(dataformat.getFormat("$#\\,###\\,##0.00"));
Sheet sheet = workbook.createSheet("Sheet1");
double value = 12345678.9;
Cell cell;
int r = 0;
sheet.createRow(r).createCell(0).setCellValue("defaultCurrency");
cell = sheet.getRow(r++).createCell(1);
cell.setCellValue(value);
cell.setCellStyle(defaultCurrency);
sheet.createRow(r).createCell(0).setCellValue("defaultUSDCurrency");
cell = sheet.getRow(r++).createCell(1);
cell.setCellValue(value);
cell.setCellStyle(defaultUSDCurrency);
sheet.createRow(r).createCell(0).setCellValue("fakeHindiCurrency");
cell = sheet.getRow(r++).createCell(1);
cell.setCellValue(value);
cell.setCellStyle(fakeHindiCurrency);
sheet.createRow(r).createCell(0).setCellValue("fakeUSDCurrency");
cell = sheet.getRow(r++).createCell(1);
cell.setCellValue(value);
cell.setCellStyle(fakeUSDCurrency);
sheet.autoSizeColumn(0);
sheet.autoSizeColumn(1);
FileOutputStream out = new FileOutputStream("CreateExcelDigitGroupings.xlsx");
workbook.write(out);
workbook.close();
out.close();
}
}
Result in Excel having Format Hindi(India) set in Windows regional settings and so default digit grouping is set to 12,34,56,789:
As you see for all default number formats the system's digit grouping is used. But my fake USD format works.
Result in OpenOffice 3.2.1 Ubuntu 18.04.1 LTS.
Please try with the following modifications to the currency formats
USformatStyle.setDataFormat(df.getFormat("$#,##0.00"));
INRformatStyle.setDataFormat(df.getFormat("₹#,##0.00"));
Finally found that Libreoffice Calc takes the regional language formatting(by default I get indian formatting)..works fine in MS excel.
Following is my code:
String monthEndDate = "31-Dec-17";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy",java.util.Locale.ENGLISH);
XSSFCell updateDateCell = sheet.getRow(rownumber).getCell(15);
XSSFCellStyle cellStyle = (XSSFCellStyle)updateDateCell.getCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("dd-MMM-yy"));
Date updateDate = sdf.parse(monthEndDate);
updateDateCell.setCellValue(updateDate);
updateDateCell.setCellStyle(cellStyle);
It is setting numeric value 43100.0
I suspect your problem is that you are getting the CellStyle via Cell.getCellStyle and then you are overwriting that CellStyle.
CellStyles are in Excel defined on Workbook level. That means, not each cell has it's own cell style but cells share cell styles defined on workbook level.
So if you do the getting the CellStyle via Cell.getCellStyle and then overwriting that CellStyle multiple times then only the last overwriting will be active. So I suspect, your complete code overwrites the same cell style, gotten from another cell, with another number format after you have overwritten it with the date number format.
The easy conclusion could be to really give each cell it's own cell style. But this is also wrong since there is a limit number of cell styles in a workbook. So we need
Having as much own cell styles as needed.
Having as much cell styles shared as possible.
To achieve this CellUtil can be used in apache poi. This provides methods only to create a new cell style if there is not already the same cell style defined in the workbook and simply to use that cell style if there is already the same cell style defined in the workbook.
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.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
public class ExcelSetDateValue {
public static void main(String[] args) throws Exception {
XSSFWorkbook wb = (XSSFWorkbook)WorkbookFactory.create(new FileInputStream("ExcelTest.xlsx"));
//possiby we need data formats
DataFormat dataFormat = wb.createDataFormat();
//get sheet and set row number
XSSFSheet sheet = wb.getSheetAt(0);
int rownumber = 3;
//get the date
String monthEndDate = "31-Dec-17";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy", java.util.Locale.ENGLISH);
Date updateDate = sdf.parse(monthEndDate);
//set date as cell value
XSSFCell updateDateCell = sheet.getRow(rownumber).getCell(15);
updateDateCell.setCellValue(updateDate);
//use CellUtil to set the CellStyleProperties
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(CellUtil.DATA_FORMAT, dataFormat.getFormat("dd-MMM-yy"));
CellUtil.setCellStyleProperties(updateDateCell, properties);
wb.write(new FileOutputStream("ExcelTestNew.xlsx"));
wb.close();
}
}
Add updateDateCell = Format(updateDateCell, "dd-MMM-yyyy") at the end of your code.
You should get 31-Dec-2017.
This is an example which I already have for formatting date, you can reuse the part of it ( I marked the relevant lines of code). It's tested and working fine, if any issue let me know.
//UPDATE
Please see Axel Richter's answer https://stackoverflow.com/a/47920182/1053496 for the correct answer. In my example, I'm storing date as String instead of Date object which is not the recommended way
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.xssf.usermodel.*;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteExcelBasic {
public static void main(String[] args) throws IOException {
String excelFileName = "/Users/home/Test3.xls";
FileOutputStream fos = new FileOutputStream(excelFileName);
XSSFWorkbook wb = new XSSFWorkbook();
XSSFCellStyle style = wb.createCellStyle();
XSSFSheet sheet = wb.createSheet("sheet");
XSSFFont urlFont = wb.createFont();
style.setFont(urlFont);
String monthEndDate = "31-Dec-17";
DataFormat df = wb.createDataFormat(); //these 3 lines are enough
short dateFormat = df.getFormat("dd-MMM-yy"); // 2nd
style.setDataFormat(dateFormat); // 3rd
for (int r = 0; r < 1; r++) {
XSSFRow row = sheet.createRow(r);
row.setHeight((short) -1);
for (int c = 0; c < 3; c++) {
XSSFCell cell = row.createCell(c);
String ss = "31-Dec-17";
cell.setCellValue(ss);
style.setWrapText(true);
cell.setCellStyle(style);
}
}
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
wb.write(baos);
byte[] myByteArray = baos.toByteArray();
fos.write(myByteArray);
fos.flush();
}
finally {
wb.close();
fos.close();
}
}
}