如何使用java避免NoSuchMethodError Create()?

时间:2013-06-07 09:39:21

标签: java apache-poi

我正在尝试将文本文件转换为Excel .......

在执行此操作时,会发生以下异常:

Exception in thread "main" java.lang.NoSuchMethodError: 
org.apache.poi.poifs.filesystem.POIFSFileSystem.hasPOIFSHeader(Ljava/io/InputStream;)Z  
at org.apache.poi.ss.usermodel.WorkbookFactory.create() 

我怎能避免这个?我正在提供我的片段。

 public void convertCSV(String textfile) throws Exception {

            FileInputStream inputStr = new FileInputStream(new File("/home/directory/Desktop/HI/excel.xls"));

            Workbook HssfWork = WorkbookFactory.create(inputStr);

            Sheet sheet= HssfWork.getSheetAt(0);
            int rowNo = 0;
            int columnNo = 0;
                     Cell cell = null;

            // Loop through the files.
            //for(File file : csvFiles) {
                Scanner scanner = new Scanner(textfile);
                while(scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    // Gets the row and if it doesn't exist it will create it.

                    Row Row = sheet.getRow(rowNo);
                    if(Row == null)
                        Row = sheet.createRow(rowNo);

                    Scanner lineScanner = new Scanner(line);
                    lineScanner.useDelimiter("\t");
                    // While there is more text to get it will loop.
                    while(lineScanner.hasNext()) {
                        // Gets the cell in that row and if it is null then it will be created.

                        org.apache.poi.ss.usermodel.Cell tempCell =Row.getCell(columnNo,org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK);
                        String output = lineScanner.next();
                        // Write the output to that cell.
                        tempCell.setCellValue(output);
                        columnNo++;
                    }
                    // Resets the column count for the new row.
                    columnNo = 0;
                    rowNo++;
                }

            // Writes the file and closes everything.
            FileOutputStream out = new FileOutputStream(excelFile);
            HssfWork.write(out);
            inputStr.close();
            out.close();
        }

2 个答案:

答案 0 :(得分:0)

首先猜测是:你的JAR版本错误了。我猜你的类路径中至少有2个JARS,WorkbookFactory在一个中,POIFSFileSystem在另一个中。检查第二个JAR的版本。

NoSuchMethodException表示它所说的内容:被调用的方法(WorkbookFactory)不存在。所以如果你得到它,就意味着类POIFSFileSystem 确实存在 - 否则你就会遇到可怕的NoClassDefFoundError。所以你必须拥有合适的库,但是它的版本不同,但尚未添加hasPOIFSHeader() ...或者已被删除...

答案 1 :(得分:0)

正如安德鲁在his answer中指出的那样,你得到了这个例外,因为你没有一套匹配的POI罐正在使用中。这有两个常见的原因。一个是你以某种方式挑选了一组不匹配的罐子,例如poi-ooxml-3.10-beta1-20130204.jarpoi-3.8-final.jar - 这些都不起作用。或者,您已将匹配集放置在类路径中,但已存在较旧的jar,并且您的类加载器已选择随机集。

无论哪种方式,我建议你按照instructions in this Apache POI FAQ Entry on the topic,找出你实际使用的POI Jars。然后,一直工作,直到你有匹配的集合。 POI与大多数应用程序一样,要求所有使用的Jars都来自相同的版本!

相关问题