Ekz0
Ekz0

Reputation: 63

How to read xlsx file using POI?

I read the xls file using POI HSSF, everything was correct. But I didn't learn how to read the input file 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. libraries. However, it throws an error:

Exception in thread "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):

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()
        }
    }

}

Upvotes: 0

Views: 1763

Answers (1)

Axel Richter
Axel Richter

Reputation: 61870

A NoSuchMethodError on run time occurs if the code runs using another library version than it was compiled with.

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.

The method public static DocumentBuilder newDocumentBuilder() was introduced in org.apache.poi.util.XMLHelper in apache poi 4.1.2. It is not present in lower versions.

Also make sure you are not mixing different apache poi versions. That is not supported and also might lead to such errors because different versions exporting different versions of methods too. See faq-N10204.

Maybe lower versions of apache poi classes are shipped from other libraries too. You can ask the ClassLoader where a special class (org.apache.poi.util.XMLHelper in your case) came from on run time:

...
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.

Upvotes: 3

Related Questions