22

質問が少しわかりにくいと思いますが、他にどのように表現すればよいかわかりませんでした。とにかく、ここに元のコードがあります:

private void readFile(String excelFileName) throws FileNotFoundException, IOException {
    XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(excelFileName));
    if (workbook.getNumberOfSheets() > 1){
        System.out.println("Please make sure there is only one sheet in the excel workbook.");
    }
    XSSFSheet sheet = workbook.getSheetAt(0);
    int numOfPhysRows = sheet.getPhysicalNumberOfRows();
    XSSFRow row;
    XSSFCell num;
    for(int y = 1;y < numOfPhysRows;y++){    //start at the 2nd row since 1st should be category names
        row = sheet.getRow(y);
        poNum = row.getCell(1);
        item = new Item(Integer.parseInt(poNum.getStringCellValue());
        itemList.add(item);
        y++;
    }
}

private int poiConvertFromStringtoInt(XSSFCell cell){
    int x = Integer.parseInt(Double.toString(cell.getNumericCellValue()));
    return x;
}

次のエラーが表示されます。

Exception in thread "main" java.lang.IllegalStateException: Cannot get a numeric value from a text cell
    at org.apache.poi.xssf.usermodel.XSSFCell.typeMismatch(XSSFCell.java:781)
    at org.apache.poi.xssf.usermodel.XSSFCell.getNumericCellValue(XSSFCell.java:199)

XSSFCell.getStringCellValue()またはを使用して文字列を取得するように変更してもXFFSCell.getRichTextValue、上記のエラー メッセージの逆が表示されます (最終的には を使用して int にするようにしていますInteger.parseInt(XSSFCell.getStringCellValue())。

エラーは次のようになります。

Exception in thread "main" java.lang.IllegalStateException: Cannot get a text value from a numeric cell
    at org.apache.poi.xssf.usermodel.XSSFCell.typeMismatch(XSSFCell.java:781)
    at org.apache.poi.xssf.usermodel.XSSFCell.getNumericCellValue(XSSFCell.java:199)

私は、Excel スプレッドシートの列が実際には文字列であることを知っています。常に同じ形式を使用し、各列を最初にフォーマットすると多くの処理時間がかかる他の場所にアップロードされているため、Excel シートを変更することはできません。

助言がありますか?

[解決策] @Wivani のヘルプから思いついた解決策コードは次のとおりです。

private long poiGetCellValue(XSSFCell cell){
    long x;
    if(cell.getCellType() == 0)
        x = (long)cell.getNumericCellValue();
    else if(cell.getCellType() == 1)
        x = Long.parseLong(cell.getStringCellValue());
    else
        x = -1;
    return x;
}
4

7 に答える 7

53
Use This as reference

switch (cell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    System.out.println(cell.getRichStringCellValue().getString());
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)) {
                        System.out.println(cell.getDateCellValue());
                    } else {
                        System.out.println(cell.getNumericCellValue());
                    }
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    System.out.println(cell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    System.out.println(cell.getCellFormula());
                    break;
                default:
                    System.out.println();
            }
于 2011-09-08T05:29:51.627 に答える
25

このセルに定義されたフォーマットを使用して、値を文字列として取得できます。

final DataFormatter df = new DataFormatter();
final XSSFCell cell = row.getCell(cellIndex);
String valueAsString = df.formatCellValue(cell);

この回答に感謝します。

于 2014-09-18T09:38:23.197 に答える
21

cell.setCellType(1); を使用するだけです。セル値を読み取る前に常に文字列として取得し、その後は独自の形式(タイプ)で使用できます。

ラヴィ

于 2012-12-10T09:28:53.277 に答える
3

以下のコードを使用して、poi を使用して xcels から任意のデータ型を読み取ります。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 * @author nirmal
 */
public class ReadWriteExcel {

    public static void main(String ar[]) {
        ReadWriteExcel rw = new ReadWriteExcel();
        rw.readDataFromExcel();

    }
    Object[][] data = null;

    public File getFile() throws FileNotFoundException {
        File here = new File("test/com/javaant/ssg/tests/test/data.xlsx");
        return new File(here.getAbsolutePath());

    }

    public Object[][] readDataFromExcel() {
        final DataFormatter df = new DataFormatter();
        try {

            FileInputStream file = new FileInputStream(getFile());
            //Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook = new XSSFWorkbook(file);

            //Get first/desired sheet from the workbook
            XSSFSheet sheet = workbook.getSheetAt(0);

            //Iterate through each rows one by one
            Iterator<Row> rowIterator = sheet.iterator();

            int rownum = 0;
            int colnum = 0;
            Row r=rowIterator.next();

            int rowcount=sheet.getLastRowNum();
            int colcount=r.getPhysicalNumberOfCells();
            data = new Object[rowcount][colcount];
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();

                //For each row, iterate through all the columns
                Iterator<Cell> cellIterator = row.cellIterator();
                colnum = 0;
                while (cellIterator.hasNext()) {

                    Cell cell = cellIterator.next();
                    //Check the cell type and format accordingly
                    data[rownum][colnum] =  df.formatCellValue(cell);
                    System.out.print(df.formatCellValue(cell));
                    colnum++;
                    System.out.println("-");
                }
                rownum++;
                System.out.println("");
            }
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }
}
于 2015-09-03T12:06:31.543 に答える
2

POI バージョン 3.12final でもこのバグが発生しました。
バグはそこに登録されていると思います: https://bz.apache.org/bugzilla/show_bug.cgi?id=56702そして、私の分析でそこにコメントを入れました。

私が使用した回避策は次のとおりです。DateUtil.isCellDateFormattedによって呼び出されたHSSFCell.getNumericCellValueによって例外が発生しました。DateUtil.isCellDateFormatted は 2 つのことを行います:
1) HSSFCell.getNumericCellValue を呼び出してから DateUtil.isValidExcelDate() を呼び出してセルの値の型を確認しますが、ここではほとんど無意味だと思います。
2) セルの形式が日付形式かどうかを確認します

上記のトピック 2) のコードを新しい関数 'myIsADateFormat' にコピーし、DateUtil.isCellDateFormatted の代わりに使用しました (ライブラリ コードをコピーするのはかなり面倒ですが、動作します...)。

private boolean myIsADateFormat(Cell cell){
    CellStyle style = cell.getCellStyle();
    if(style == null) return false;
    int formatNo = style.getDataFormat();
    String formatString = style.getDataFormatString();
    boolean result = DateUtil.isADateFormat(formatNo, formatString);
    return result;
}

最初に値の型を確認する必要がある場合は、これも使用できます。

CellValue cellValue = evaluator.evaluate(cell);
int cellValueType = cellValue.getCellType();
if(cellValueType == Cell.CELL_TYPE_NUMERIC){
    if(myIsADateFormat(cell){
        ....
    }
}
于 2015-09-03T13:06:06.933 に答える
1

ドキュメントには、CellType を 1 に設定しないで、代わりに Thierry が説明したように DataFormatter を使用しないことが明確に記載されています。

https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#setCellType(int)

于 2015-06-29T21:04:24.300 に答える
0

Ravi のソリューションは機能します: cell.setCellType(1); を使用するだけです。セル値を読み取る前に常に文字列として取得し、その後は独自の形式(タイプ)で使用できます。

于 2014-07-02T06:41:28.473 に答える