JExcel/POI: Creating a cell as type Text

user1411138 picture user1411138 · May 22, 2012 · Viewed 9.4k times · Source

I have a requirement that involves reading values from an excel spreadsheet, and populating a spreadsheet for users to modify and re-upload to our application. One of these cells contains a text string of 5 characters that may be letters, numbers, or a combination of both. Some of these strings contain only numbers, and begin with a zero. Because of this, the cell type is Text; however, when I use Apache POI or JExcel to populate a spreadsheet for the users to modify it is always set as cell type General.

Is there a way using either of these libraries, or some other excel api that I have not seen yet, to specify that a cell have type Text?

Answer

user1411138 picture user1411138 · May 23, 2012

My co-worker just found a way to accomplish this. In JExcel, it can be accomplished by using a WritableCellFormat such as:

WritableCellFormat numberAsTextFormat = new WritableCellFormat(NumberFormats.TEXT);

Then, when you are creating your cell to add to a sheet you just pass in the format as normal:

Label l = new Label(0, 0, stringVal, numberAsTextFormat);

If you are using Apache POI, you would create a HSSFCellStyle, and then set it's data format like this:

HSSFCellStyle style = book.createCellStyle();
style.setDataFormat(BuiltInFormats.getBuiltInFormat("text"));