如何使用poi在java中读取excel(.xlsx)?

时间:2013-05-03 11:23:45

标签: java apache-poi

我正在尝试在java中读取excel。我有以下代码。

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Test {
    public static void main(String[] args) throws IOException {
        String fname = "D:\\Test.xlsx"; // or "C:\\Test.xls" C:\\SDI-XL.xls
        InputStream inp = new FileInputStream(fname);
        Workbook  wb = new XSSFWorkbook(inp); // Declare XSSF WorkBook
        Sheet sheet = wb.getSheetAt(0); // sheet can be used as common for XSSF and HSSF

        Iterator<Row> rows=sheet.rowIterator();
        while (rows.hasNext()) {
            Row row = (Row) rows.next();
            System.out.println("row#=" + row.getRowNum() + "");
            Iterator cells = row.cellIterator();
            while (cells.hasNext()) {
                Cell cell = (Cell) cells.next();

                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:
                }
            }
        }
        inp.close();
    }
}

我导入了poi.3.6jar和poi.ooxml-3.6 jar。 当我运行此程序时,我收到以下错误消息。

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException
    at Test.main(Test.java:16)
Caused by: java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlException
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 1 more

我不明白为什么会出现这个错误消息。所以请帮助我。

5 个答案:

答案 0 :(得分:11)

xmlbeans-2.3.0.jar文件添加到您的类路径中。

答案 1 :(得分:11)

添加以下jar文件:

  • poi-3.9.jar
  • poi-ooxml-3.9.jar
  • poi-ooxml-schemas-3.7.jar
  • xmlbeans-2.3.0.jar
  • DOM4J-1.6.1.jar

答案 2 :(得分:1)

添加

xmlbeans-2.3.0.jar
dom4j-1.6.1.jar 

与常规POI XML一起,肯定会解决问题。

答案 3 :(得分:0)

使用此: 输入字符串filePath 输出是json对象列表的列表

Have these dependencies
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.9</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-collections4</artifactId>
        <version>4.0</version>
    </dependency>


/**
 * Function reads the input excel and gives list(sheet) of objects(rows of each sheet)
 * @param filePath
 * @return list of list of json objects
 */
public static List<List> excelFileReader(String filePath){

    List<List>totalSheetList=new ArrayList<>();
    XSSFWorkbook workbook= null;
    try {
        workbook = new XSSFWorkbook(filePath);
    } catch (IOException e) {
        e.printStackTrace();
    }

    //iteration for sheets in a workbook
    for(int sheetIndex=0;sheetIndex<workbook.getNumberOfSheets();sheetIndex++){
        XSSFSheet sheet=workbook.getSheetAt(sheetIndex);
        XSSFRow row=null;
        List<JSONObject> singleSheetList=new ArrayList<>();

        //excel header - first row and non-empty
        String[] header=new String[sheet.getRow(0).getPhysicalNumberOfCells()];
        if (sheet.getPhysicalNumberOfRows()!=0 && sheet.getRow(0).getRowNum()==0) {
            row=sheet.getRow(0);
            for(int index=0;index<row.getPhysicalNumberOfCells();index++){
                header[index]=(row.getCell(index).getStringCellValue());
            }
        }

        //if header exists , start reading the values excluding first row (header)
        if(header.length!=0){
            for(int rowIndex=1;rowIndex<sheet.getPhysicalNumberOfRows();rowIndex++){
                row=sheet.getRow(rowIndex);
                HashMap<String,Object> eachRow=new HashMap<>();
                for(int colIndex=0;colIndex<header.length;colIndex++) {
                    String cell = "";
                    if(row.getCell(colIndex)==null){
                        cell="";
                    }else{
                        if(row.getCell(colIndex).getCellType()==Cell.CELL_TYPE_STRING){
                            cell = row.getCell(colIndex).getRichStringCellValue().toString();
                        }else{
                            row.getCell(colIndex).setCellType(Cell.CELL_TYPE_STRING);
                            cell=row.getCell(colIndex).getStringCellValue();
                        }
                    }
                    eachRow.put(header[colIndex], cell);
                }
                JSONObject eachRowJsonObject = new JSONObject(eachRow);
                singleSheetList.add(eachRowJsonObject);
            }
        }
        totalSheetList.add(singleSheetList);
    }
    return totalSheetList;
}

答案 4 :(得分:-1)

添加以下jar并将它们添加到类路径中,然后运行您的项目。

  1. DOM4J-1.6.1-sources.jar
  2. dom4j.jar
  3. 的log4j-1.2.17.jar
  4. POI-3.5 FINAL.jar
  5. POI-OOXML-3.5 beta5.jar
  6. POI-OOXML-架构-3.9.jar
  7. 的xmlbeans-2.3.0.jar