1

我想使用 apache poi api 在 java 中读取 2010 excel 文件...但它给了我一个错误线程“main”java.lang.IllegalArgumentException 中的异常:工作表索引(0)超出范围(0..-1 ) 我正在使用 xssf,但如果我想从旧格式的 excel 中获取数据,那么它可以通过唱 HSSF 来正常工作。我不知道 XSSF 发生了什么..这是我的代码..请帮助我。

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * This java program is used to read the data from a Excel file and display them
 * on the console output.
 * 
 * @author dhanago
 */
public class xssff {

    /** Creates a new instance of POIExcelReader */
    public xssff() {
    }

    /**
     * This method is used to display the Excel content to command line.
     * 
     * @param xlsPath
     */
    @SuppressWarnings("unchecked")
    public void displayFromExcel(String xlsPath) {
        InputStream inputStream = null;

        try {
            inputStream = new FileInputStream(xlsPath);
        } catch (FileNotFoundException e) {
            System.out.println("File not found in the specified path.");
            e.printStackTrace();
        }


        XSSFWorkbook workBook = new XSSFWorkbook();
        XSSFSheet sheet = workBook.getSheetAt(1);
        Iterator<Row> rows = sheet.rowIterator();

        while (rows.hasNext()) {
            XSSFRow row = (XSSFRow) rows.next();

            // display row number in the console.
            System.out.println();

            // once get a row its time to iterate through cells.
            Iterator<Cell> cells = row.cellIterator();

            while (cells.hasNext()) {
                XSSFCell cell = (XSSFCell) cells.next();

                /*
                 * Now we will get the cell type and display the values
                 * accordingly.
                 */
                switch (cell.getCellType()) {
                case XSSFCell.CELL_TYPE_NUMERIC: {

                    // cell type numeric.
                    System.out.print(cell.getNumericCellValue() + "\t\t\t");

                    break;
                }

                case XSSFCell.CELL_TYPE_STRING: {

                    // cell type string.
                    XSSFRichTextString richTextString = cell
                            .getRichStringCellValue();

                    System.out.print(richTextString.getString() + "\t\t\t");

                    break;
                }

                default: {

                    // types other than String and Numeric.
                    System.out.println("Type not supported.");

                    break;
                }
                }
            }
        }

    }

    /**
     * The main executable method to test displayFromExcel method.
     * 
     * @param args
     */
    public static void main(String[] args) {
        xssff poiExample = new xssff();
        String xlsPath = "c://temp//data.xlsx";

        poiExample.displayFromExcel(xlsPath);
    }
}
4

2 回答 2

5

好的,我发现了您的问题,您正在创建一本没有工作表的新书

XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.getSheetAt(1);  //error here, the workBook book has NO sheets!

您应该基于 InputStream 创建这本书

XSSFWorkbook workBook = WorkbookFactory.create(new PushbackInputStream(inputStream));
XSSFSheet sheet = workBook.getSheetAt(1);

或者更简单,只需传递文件名即可创建图书:

XSSFWorkbook workBook = new XSSFWorkbook(xlsPath);
XSSFSheet sheet = workBook.getSheetAt(1);
于 2012-07-02T06:57:28.597 回答
1

尝试这个:

// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = createSheet(workbook, "Sheet 1", false);
XSSFRow row1 = sheet.createRow(0);

该功能是:

    private static XSSFSheet createSheet(XSSFWorkbook wb, String prefix, boolean isHidden) {
    XSSFSheet sheet = null;
    int count = 0;

    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        String sName = wb.getSheetName(i);
        if (sName.startsWith(prefix))
            count++;
    }

    if (count > 0) {
        sheet = wb.createSheet(prefix + count);
    } else
        sheet = wb.createSheet(prefix);

    if (isHidden)
        wb.setSheetHidden(wb.getNumberOfSheets() - 1, XSSFWorkbook.SHEET_STATE_VERY_HIDDEN);

    return sheet;
}
于 2017-05-16T20:47:17.260 回答