I need to generate an .xls (Excel) file, using the Java library Apache POI for spreadsheets.
The file will contain a list of phone numbers in column A, formatted as "0221...." or "+49221..." - so Excel by default interprets them as numeric cells. This is bad, because the leading 0 or + will get trimmed.
To solve the problem, I can use cell.setCellType(Cell.CELL_TYPE_STRING)
, which works fine, but only for the specific cells I set this for.
How can I apply this setting for the entire column (i.e. even for all the remaining cells, where the user will enter additional phone numbers)?
In Excel, this is possible: Selecting the entire column, and apply the cell type (the setting survives saving/loading the file.)
But I can't find the correct method for POI.
sheet.setDefaultCellType(int colNum)
. But I can't find anything like this (probably I'm just blind? There are lots of similar methods in the library for applying text styles like "align center" etc.)createRow((int)0); CellStyle style=headRow. getRowStyle(); Font boldFont=hwb. createFont(); boldFont.
To create date cell which display current date to the cell, we can use Apache POI's style feature to format the cell according to the date. The setDateformat() method is used to set date format.
Apache POI uses the Workbook interface to represent an Excel file. It also uses Sheet, Row, and Cell interfaces to model different levels of elements in an Excel file. At the Cell level, we can use its getCellType() method to get the cell type.
Here's some example code inspired by Vlad's answer:
DataFormat fmt = workbook.createDataFormat();
CellStyle textStyle = workbook.createCellStyle();
textStyle.setDataFormat(fmt.getFormat("@"));
worksheet.setDefaultColumnStyle(0, textStyle);
The above code sets the default style for the first column of worksheet to TEXT.
Thanks, Vlad!
A better way to set it now using POI is to use the BuiltinFormats
class.
Eg:
To convert the column type to numeric
CellStyle numericStyle = workbook.createCellStyle();
numericStyle.setDataFormat(BuiltinFormats.getBuiltinFormat(2)); // 2 For Number
worksheet.setDefaultColumnStyle(colId, numericStyle);
The complete list of BuiltinFormats
formats can be seen, here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With