1

我正在尝试使用 apache poi 读取 excel 文件(xls)文件。在那,如果一个单元格丢失(cellIterator)在读取行期间跳过该单元格并将下一个值放入不同的标题。

美国广播公司

1 2 3

4 空白 6

在上述情况下,它将 6 放在空白单元格的“B”列中,我需要 B 作为空白字符串。

`package com.howtodoinjava.demo.poi;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class ReadExcelDemo {

    Integer rowNum;
    Iterator<Row> rowIterator;
    HSSFWorkbook workbook;
    HSSFSheet sheet;
    FileInputStream file;

    public ReadExcelDemo(File file1) throws IOException{
         this.file = new FileInputStream(file1);

        // Create Workbook instance holding reference to .xlsx file
        this.workbook = new HSSFWorkbook(file);
        workbook.setMissingCellPolicy(Row.CREATE_NULL_AS_BLANK);

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

    public static void main(String[] args) throws IOException {


        for(int i =0;i<5;i++) {
            List<String> rowData = new ReadExcelDemo(new File(
                    "howtodoinjava_demo_xls.xls")).readRow();
            System.out.println(rowData);
        }

    }

    private List<String> readRow() throws IOException {
        List<String> rowData = new ArrayList<String>();

            // Iterate through each rows one by one
            rowIterator = sheet.iterator();
            if (getNext()) {
                Row row = rowIterator.next();
                // For each row, iterate through all the columns
                Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    // Check the cell type and format accordingly
                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_NUMERIC:
                        rowData.add(String.valueOf(cell.getNumericCellValue()));
                        System.out.print(cell.getNumericCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_STRING:
                        rowData.add(cell.getStringCellValue());
                        System.out.print(cell.getStringCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_BLANK:
                        rowData.add("");
                        System.out.println("");
                    }
                }
                System.out.println("");
            }
            rowNum++;
            close();


        return rowData;
    }

    private void close() throws IOException {
        file.close();
    }

    private boolean getNext() {
        // TODO Auto-generated method stub
        if (null == rowNum) {
            rowNum = 0;
        }
        return rowIterator.hasNext();
    }
}
`

这是代码片段。我试过 workbook.setMissingCellPolicy(Row.CREATE_NULL_AS_BLANK); 但它不工作。任何建议为什么会发生?

4

3 回答 3

1

我已经使用 iterator for row 逐一读取行,使 rowIterator 类级别,然后使用 for 循环遍历列并完全控制行数据并将策略设置为“将 null 创建为空白”。

final Row row = this.sheet.getRow(rowNum);

if (null != row) {

    int lastColumn = row.getLastCellNum();
    // Removing cellIterator as it was not supporting
    // MissingCellPolicy and doing the column iteration through for
    // loop
    for (int cn = Constants.EMPTY_INT; cn < lastColumn; cn++) {
        Cell cell = row.getCell(cn, Row.CREATE_NULL_AS_BLANK);

        switch (cell.getCellType()) {
        case Cell.CELL_TYPE_NUMERIC:
            addNumericCell(rowData, cell);
            break;
        case Cell.CELL_TYPE_STRING:
            rowData.add(cell.getStringCellValue());
            break;
        case Cell.CELL_TYPE_BLANK:
            rowData.add(Constants.EMPTY_STRING);
            break;
        default:
            break;

        }
    }
}

apache poi的有用链接。

于 2015-02-03T10:10:56.857 回答
0

使用 POI 3.10 工作的简化代码。下面的代码将工作表数据作为列表返回,并适用于具有 NULL 值的单元格。

/**
     * Read XLSx and return sheet data as List
     * 
     * @param inputFile
     * @param sheetNo
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static List<String> readXlsxAsList(File inputFile, int sheetNo) throws FileNotFoundException,
            IOException {

        List<String> sheetAsList = new ArrayList<String>();
        /**
         * Get workbook
         */
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(inputFile));
        /**
         * Get sheet
         */
        XSSFSheet sheet = wb.getSheetAt(sheetNo);
        Iterator<Row> rowIterator = sheet.iterator();
        /**
         * Iterate Rows
         */
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            StringBuffer sb = new StringBuffer();
            for (int col = 0; col < row.getLastCellNum(); col++) {
                /**
                 * Create cell to force as BLANK when NULL
                 */
                Cell cell = row.getCell(col, Row.CREATE_NULL_AS_BLANK);
                /**
                 * Force cell type as String
                 */
                cell.setCellType(Cell.CELL_TYPE_STRING);
                /**
                 * Add to buffer
                 */
                sb.append(cell.getStringCellValue() + "|");
            }
            /**
             * Add buffer to list
             */
            sheetAsList.add(sb.toString());
        }
        return sheetAsList;
    }
于 2015-03-24T04:07:55.280 回答
0
Similar to issue: https://stackoverflow.com/questions/19711603/apache-poi-xlsx-read-cell-with-value-error-unexpected-cell-type5/68892155#68892155

This issue also got resolved using the same logic.
  
  I too faced the same error while working on Spring batch insert excel data to DB.
    
    I was using spring-batch-excel version 0.5.0 and poi 3.12
    
    <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-excel</artifactId>
            <version>0.5.0-SNAPSHOT</version>
        </dependency>
    
    Once Updated to spring-batch-excel version 1.0.1 and poi 3.17, It was resolved.
    
        <dependency>
            <groupId>com.github.kumarpankaj18</groupId>
            <artifactId>spring-batch-excel</artifactId>
            <version>1.0.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
         </dependency>
于 2021-08-23T11:52:59.307 回答