简体   繁体   English

如何使用 POI 读取 xlsx 文件?

[英]How to read xlsx file using POI?

I read the xls file using POI HSSF, everything was correct.我使用 POI HSSF 读取了 xls 文件,一切正常。 But I didn't learn how to read the input file xlsx.但是我没有学会如何读取输入文件xlsx。 Previously, I did not work with xlsx, I read the material on the network on different resources, I did not notice the difference except for replacing HSSF with XSSF and connecting additional.之前没用过xlsx,看了网络上不同资源上的资料,除了用XSSF替换HSSF并额外连接外,没发现有什么区别。 libraries.图书馆。 However, it throws an error:但是,它会引发错误:

Exception in thread "main" java.lang.NoSuchMethodError: org.apache.poi.util.XMLHelper.newDocumentBuilder () Ljavax / xml / parsers / DocumentBuilder;线程“main”中的异常 java.lang.NoSuchMethodError: org.apache.poi.util.XMLHelper.newDocumentBuilder() Ljavax/xml/parsers/DocumentBuilder;

Swears at发誓

XSSFWorkbook wb = new XSSFWorkbook (p_file);
def res = SSC.execute (connection, file, "test.xlsx")

The code is given below (I will be very grateful if anyone can help in solving the problem now / on ";" do not pay attention, because I use groovy, the rest is similar to java):代码如下(如果有人能帮忙解决现在/上“;”的问题,我将不胜感激,不要关注,因为我用的是groovy,其余的和java类似):

import groovy.sql.Sql
import org.apache.poi.xssf.usermodel.XSSFCell

import javax.xml.soap.Text
import java.sql.Blob
import java.sql.Connection
import java.sql.DriverManager

import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.usermodel.*

import org.apache.poi.xssf.usermodel.XSSFWorkbook; //New imports to read XLSX format
import org.apache.poi.xssf.usermodel.XSSFSheet; //New imports to read XLSX format
import org.apache.poi.ss.usermodel.*;
import java.util.Iterator;


import java.io.*;

class XM_PARSE_XLS {

    def execute(Connection conn, InputStream p_file, String p_filename) {



        Sql sql = new Sql(conn)

        XSSFWorkbook wb = new XSSFWorkbook(p_file);

        ArrayList<HashMap<String, String>> arrAllData = new ArrayList<HashMap<String, String>>();

        String strsql
        Integer cntStr = 0
        HashSet rw_okpo = new HashSet();

        // идем по листам в файле
        wb.each { XSSFSheet myExcelSheet ->
            DataFormatter formatter = new DataFormatter(Locale.ROOT);

            // идем по страницам файла
            myExcelSheet.each{  Row myrow ->

                HashMap<String, String> hm = new HashMap<String, String>();

                if (cntStr >= 0) {
                    // идем по строкам с данными
                    Integer numCell = 0;
                    String typ = '';

                    myrow.each { Cell mycell ->
                        String value = ""; // приводит любые ячейки к строковому формату

                        // если тип Строка
                        if (mycell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
                            value = mycell.getStringCellValue();
                            typ = 'S'
                            // если тип число
                        }  else {
                            // а для числовых ячеек или ячеек даты значение будет отформатировано на основе правил форматирования / стиля, примененных к ячейке, а затем возвращено как строка
                            value = formatter.formatCellValue(mycell);
                            value = value.replace(',','');
                            typ = 'N'
                            if (cntStr >= 0){
                            switch(numCell) { //0-17
                                case 0:
                                    hm.put("t0", value + ";");
                                    break;
                                case 1:
                                    hm.put("t1", value + ";");
                                    break;
                                case 2:
                                    hm.put("t2", value + ";");
                                    break;
                                case 3:
                                    hm.put("t3", value + ";");
                                    break;
                                case 4:
                                    hm.put("t4", value + ";");
                                    break;
                                case 5:
                                    hm.put("t5", value + ";");
                                    break;
                                case 6:
                                    hm.put("t6", value + ";");
                                    break;
                                case 7:
                                    hm.put("t7", value + ";");
                                    break;
                                case 8:
                                    hm.put("t8", value + ";");
                                    break;
                                case 9:
                                    hm.put("t9", value + ";");
                                    break;
                                case 10:
                                    hm.put("t10", value + ";");
                                    break;
                                case 11:
                                    hm.put("t11", value + ";");
                                    break;
                                case 12:
                                    hm.put("t12", value + ";");
                                    break;
                                case 13:
                                    hm.put("t13", value + ";");
                                    break;
                                case 14:
                                    hm.put("t14", value + ";");
                                    break;
                                case 15:
                                    hm.put("t15", value + ";");
                                    break;
                                case 16:
                                    hm.put("t16", value + ";");
                                    break;
                                case 17:
                                    hm.put("t17", value + "\r\n");
                                    break;
                            }
                            numCell = numCell + 1;

                        }

                    }
                }
                if(hm) arrAllData.add(hm);
                cntStr = cntStr + 1;
            }
        }



        return res;
    }
    static void main(String... args) {
        Class.forName("oracle.jdbc.driver.OracleDriver")
        //Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@10.193.21.75:3333/OLAP2", "LAS", "ASfDER7F4FA")
        connection.setAutoCommit(true)

        try {

            def file = new File("test.xlsx").newInputStream()
            def SSC = new XM_PARSE_XLS()
            def res = SSC.execute(connection,file,"test.xlsx")

        } finally {
            connection.close()
        }
    }

}

A NoSuchMethodError on run time occurs if the code runs using another library version than it was compiled with.如果代码运行时使用的库版本不同于编译时使用的库版本,则会在运行时发生NoSuchMethodError

Here the code probably was compiled using apache poi 4.1.2 but on run time there is a lower version of apache poi used.这里的代码可能是使用apache poi 4.1.2编译的,但在运行时使用了较低版本的apache poi

The method public static DocumentBuilder newDocumentBuilder() was introduced in org.apache.poi.util.XMLHelper in apache poi 4.1.2 .方法public static DocumentBuilder newDocumentBuilder()是在apache poi 4.1.2 org.apache.poi.util.XMLHelper中引入的。 It is not present in lower versions.它在较低版本中不存在。

Also make sure you are not mixing different apache poi versions.还要确保您没有混合不同的apache poi版本。 That is not supported and also might lead to such errors because different versions exporting different versions of methods too.这不受支持,也可能导致此类错误,因为不同的版本也导出不同版本的方法。 See faq-N10204 .请参阅常见问题解答-N10204

Maybe lower versions of apache poi classes are shipped from other libraries too.也许较低版本的apache poi类也来自其他库。 You can ask the ClassLoader where a special class ( org.apache.poi.util.XMLHelper in your case) came from on run time:您可以询问ClassLoader一个特殊的类(在您的例子中是org.apache.poi.util.XMLHelper )在运行时来自哪里:

...
ClassLoader classloader = org.apache.poi.util.XMLHelper.class.getClassLoader();
java.net.URL res = classloader.getResource("org/apache/poi/util/XMLHelper.class");
String path = res.getPath();
System.out.println("XMLHelper came from " + path);
...

If that is not the jar you expect, you get at least an idea which other library ships that class too.如果这不是您期望的jar ,您至少可以了解其他图书馆也提供该类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM