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 \"02
Vlad: This got most of the problem done. I found that all the empty rows were formatted the way I wanted them. However rows where I had initial zeros looked and worked fine; however if I had to change a pre-existing value with another value starting with zero the zeroes disappeared. So I recommend adding code to when you create the value in the cell to reset the the setCellStyle to text. here are some snippets: method public Cell createCell(Row r!, BBjNumber cell, BBjString value!)
c!=#this!.createCell(r!, cell)
c!.setCellValue(value!)
c!.setCellStyle(#text_format!)
methodret c!
#text_format! = #wb!.createCellStyle()
#text_format!.setDataFormat(#format!.getFormat("@"))
methodend
this may help some other sole searching for initial zeroes. Thank you for posting. Alex
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
Will this help?
By creating a data format with the @ symbol and using that in a CellStyle object that is then passed to the setDefaultColumnStyle() method, it was possible to set the default data type of the column to, in this case, text. I have not experiemented further but do suspect it would be possible to do something similar with other style objects to set the default type to numeric or even a customised format such as currency.