设置单元格类型错误

时间:2017-04-22 11:16:40

标签: java excel

我正在使用Apache POI读取包含一些数值的excel文件,我想将其转换为字符串

当我输入cell.setCellType(Cell.CELL_TYPE_STRING);时,它显示如下(http://imgur.com/a/hZvUl)并得到NullPointerException

任何人都可以帮助我吗?

public void CreateDir() throws IOException {
    try {
        if (getStartAvailablility() == false) {
            JOptionPane.showMessageDialog(null, "Please Choose Where To Save The Files First!!");
        } else {
            JOptionPane.showMessageDialog(null, "Working On It Please Wait..");
            btnStart.setEnabled(false);

            FileInputStream fis = new FileInputStream(getChooseFilepath());
            XSSFWorkbook wb = new XSSFWorkbook(fis);
            XSSFSheet sheet = wb.getSheetAt(0);
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {

                XSSFRow row = sheet.getRow(i);
                XSSFCell cell = row.getCell(2);

                cell.setCellType(Cell.CELL_TYPE_STRING);
                try {
                    if (cell != null) {
                        File dir = new File(getWorkSpacePath() + "\\" + cell);
                        // if the directory does not exist, create it
                        //System.out.println(Files.list(Paths.get(getWorkSpacePath()+dir.getName())).count());

                        if (!dir.exists()) {
                            try {
                                dir.mkdir();

                            } catch (SecurityException se) {
                                se.printStackTrace();
                            }
                        }

`

1 个答案:

答案 0 :(得分:0)

public void CreateDir() throws IOException {
    //....

    XSSFCell cell = row.getCell(2);
    cell.setCellValue(getCellValue(cell)); 
    //Value of cell is converted to String. 
    //Setting a cell to a string value sets the cell type to a String.

    //....
}

//helper method that grabs cell value regardless of type, and converts to String
public static String getCellValue(Cell cell){
    String a = "";
    int b;
    double c;
    if(cell != null){
        int type = cell.getCellType();
        switch (type) {
            case Cell.CELL_TYPE_NUMERIC:
                c = cell.getNumericCellValue();
                if(c%1 == 0){
                    b = (int) c;
                    a = b + "";
                }else{
                    a = c + "";
                }
                break;
            case Cell.CELL_TYPE_STRING:
                a = cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_FORMULA:
                a = cell.getCellFormula() + "";
                break;
            case Cell.CELL_TYPE_BLANK:
                a = "";
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                a = cell.getBooleanCellValue() + "";
                break;
            default:
                break;
        }
    }
    return a;
}