简体   繁体   English

使用 poi 或 jxl api 转换 Excel 单元格值类型

[英]Convert Excel cell value type using poi or jxl api

I have an Excel file that contains numerical values, but they are stored as labels.我有一个包含数值的 Excel 文件,但它们存储为标签。 So I want to use jxl or poi api to set their values type.所以我想使用 jxl 或 poi api 来设置它们的值类型。 However I don't know which method to use.但是我不知道使用哪种方法。

How can I do this?我怎样才能做到这一点?

I use poi library and this is my ExcelParser Class:我使用 poi 库,这是我的 ExcelParser 类:

public class ExcelParser {

    private HSSFWorkbook wb;

    public ExcelParser(File xlsFile) throws Exception{

        wb = new HSSFWorkbook(new FileInputStream(xlsFile));
    }

    public String getValue(String sheetName, int rowNum, int celNum) throws Exception{
        try{
            HSSFSheet sheet = null;
            for(int i=0; i<wb.getNumberOfSheets();i++){
                if(wb.getSheetName(i).trim().toLowerCase().equals(sheetName.trim().toLowerCase())){
                    sheet = wb.getSheetAt(i);
                    break;
                }
            }
            if(sheet == null){
                throw new Exception("Sheet name '"+sheetName+"' not found.");
            }

            HSSFRow row     = sheet.getRow(rowNum);        
            if(row == null){return "";}
            HSSFCell cell   = row.getCell(celNum);
            if(cell== null){return "";}

            if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
                return String.valueOf(cell.getNumericCellValue()).trim();
            } else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING){
                return cell.getStringCellValue().trim();        
            }  else if (cell.getCellType() == HSSFCell.CELL_TYPE_ERROR){
                return "";//cell.getErrorCellValue();        
            }else if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){
                try{

                    return cell.getStringCellValue().trim();
                } catch (Exception e) {
                    return "";
                }
            } else{
                return cell.getStringCellValue().trim();
            }
        }
        catch (Exception e) {
            throw new Exception(e.getMessage()+" in row:"+rowNum+" col:"+celNum+" sheet:"+sheetName);
        }
    }
}

WARNING, this class is for xls file only, if you use an xlsx file you have to use警告,此类仅适用于 xls 文件,如果您使用 xlsx 文件,则必须使用

XSSF 

class rather than类而不是

HSSF

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM