JExcel / POI:将单元格创建为文本类型

时间:2012-05-22 20:45:44

标签: apache-poi jexcelapi

我的要求是从excel电子表格中读取值,并填写电子表格供用户修改并重新上传到我们的应用程序。其中一个单元格包含5个字符的文本字符串,可以是字母,数字或两者的组合。其中一些字符串仅包含数字,并以零开头。因此,单元格类型为Text;但是,当我使用Apache POI或JExcel填充电子表格供用户修改时,它总是被设置为单元格类型General。

有没有办法使用这些库中的任何一个,或者我还没有看到的其他一些excel api来指定单元格是否有Text类型?

2 个答案:

答案 0 :(得分:8)

我的同事刚刚找到了实现这一目标的方法。在JExcel中,可以使用WritableCellFormat来完成,例如:

WritableCellFormat numberAsTextFormat = new WritableCellFormat(NumberFormats.TEXT);

然后,当您创建要添加到工作表的单元格时,您只需按正常格式传递:

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

如果您正在使用Apache POI,您将创建一个HSSFCellStyle,然后设置它的数据格式如下:

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

答案 1 :(得分:2)

很多时候,当用户在单元格中输入数字(格式化)是文本(字符串)时,电子表格软件(openoffice或msoffice)会自动更改其格式。我正在使用apache poi,这就是我编写代码的方式:

cell = row.getCell(); 
switch (cell.getCellType()) {

case HSSFCell.CELL_TYPE_STRING:
    value = cell.getRichStringCellValue().getString();
    break;
case HSSFCell.CELL_TYPE_NUMERIC:
    // if cell fomratting or cell data is Numeric
    // Read numeric value
    // suppose user enters 0123456 (which is string), in numeric way it is read as 123456.0
    // Now I want ot read string and I got number...Problem?????

    //well this is the solution
    cell.setCellType(Cell.CELL_TYPE_STRING);   // set cell type string, so it will retain original value "0123456"
    value = cell.getRichStringCellValue().getString(); // value read is now "0123456"    
    break;
default:
}
相关问题