0

Good

I am trying to read an Excel file (.xlsx) in a java application for a jtable by directly dragging the Excel file to the Jtable to fill it with the Excel data, I am getting multiple errors which I think are caused by the libraries used.

The libraries I am using:

  • dom4j-1.6.jar
  • org-apache-commons-codec.jar
  • poi-4.1.0.jar
  • poi-ooxml-4.1.0.jar
  • poi-ooxml-schemas-4.1.0.jar
  • stax-api-1.0.1.jar
  • xmlbeans-3.1.0

I leave part of the code of the class that I am using to achieve the reading of the Excel file:

import java.awt.HeadlessException;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class DropXlsx implements DropTargetListener {
   
    private JTable jtable;
    private DefaultTableModel tableModel;
    protected DropTarget dropTarget;

public DropXlsx() {
    }

    public void setJtable(JTable jtable) {
        this.jtable = jtable;
        dropTarget = new DropTarget(jtable, this);    
        tableModel = new DefaultTableModel();
    }

    @Override
    public void dragEnter(DropTargetDragEvent dtde) {/*...*/
    }

    @Override
    public void dragOver(DropTargetDragEvent dtde) {/*...*/
    }

    @Override
    public void dropActionChanged(DropTargetDragEvent dtde) {/*...*/
    }

    @Override
    public void dragExit(DropTargetEvent dte) {/*...*/
    }

    @Override
    public void drop(DropTargetDropEvent dtde) {
        try {
           
            Transferable tr = dtde.getTransferable();
            
            DataFlavor[] flavors = tr.getTransferDataFlavors();
            if (flavors.length > 0) {
                
                if (flavors[0].isFlavorJavaFileListType()) {
                    dtde.acceptDrop(DnDConstants.ACTION_COPY);
                    
                    java.util.List list = (java.util.List) tr.getTransferData(flavors[0]);
                    if (!list.isEmpty()) {
                        
                        File file = new File(list.get(0).toString());
                        if (file.exists()) {
                           
                            if (file.getName().endsWith("xlsx")) {
                                readXLSX(file);
                            } else {
                                JOptionPane.showMessageDialog(null, "This is not a valid * .xlsx file", "Error", JOptionPane.ERROR_MESSAGE);
                            }
                        } else {
                            System.err.println("file does not exist error ");
                        }
                    }
                    dtde.dropComplete(true);
                    return;
                }
            }
            dtde.rejectDrop();
        } catch (UnsupportedFlavorException | IOException | HeadlessException ex) {
            System.err.println("Error 1" + ex.getMessage());
            dtde.rejectDrop();
        }
    }


Up to this point I am getting an error note in checking the .xlsx file shown above:

...

if (file.getName().endsWith("xlsx")) {
                                readXLSX(file);
                            } else

...

I continue with the read function where I am also getting various errors:

private void readXLSX(File file) {        
        tableModel = new DefaultTableModel();
        try {
            XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(file));
            XSSFSheet sheet = wb.getSheetAt(0);//primeta hoja            
            Row row;
            Cell cell;

            int maxCol = 0;
            for (int a = 0; a <= sheet.getLastRowNum(); a++) {
                if(sheet.getRow(a)!=null){
                    if (sheet.getRow(a).getLastCellNum() > maxCol) {
                        maxCol = sheet.getRow(a).getLastCellNum();
                    }    
                }                
            }
            if (maxCol > 0) {
 
                for (int i = 1; i <= maxCol; i++) {
                    tableModel.addColumn("Col." + i);
                }                

                Iterator<Row> rowIterator = sheet.iterator();
                while (rowIterator.hasNext()) {

                    int index = 0;
                    row = rowIterator.next();

                    Object[] obj = new Object[row.getLastCellNum()];
                    Iterator<Cell> cellIterator = row.cellIterator();

                    while (cellIterator.hasNext()) {
                        cell = cellIterator.next();

                        while (index < cell.getColumnIndex()) {
                            obj[index] = "";
                            index += 1;
                        }

                        switch (cell.getCellType()) {
                            case BOOLEAN:
                                obj[index] = cell.getBooleanCellValue();
                                break;
                            case NUMERIC:
                                obj[index] = cell.getNumericCellValue();
                                break;
                            case STRING:
                                obj[index] = cell.getStringCellValue();
                                break;
                            case BLANK:
                                obj[index] = " ";
                                break;
                            case FORMULA:
                                obj[index] = cell.getCellFormula();
                                break;                           
                            default:
                                obj[index] = "";
                                break;
                        }                        
                        index += 1;
                    }
                    tableModel.addRow(obj);
                }
                jtable.setModel(tableModel);
            }else{
                JOptionPane.showMessageDialog(null, "Nothing to matter", "Error", JOptionPane.ERROR_MESSAGE);
            }
        } catch (IOException ex) {
            System.err.println("Error 2" + ex.getMessage());
        }
    }
    
} //DropXlsx:end

In this case I am getting the list of errors from the start of the try in reading the file.

XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(file));

Finally, leave the errors generated:

Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/apache/commons/collections4/ListValuedMap
    at clases.DropXlsx.readXLSX(DropXlsx.java:106)
    at clases.DropXlsx.drop(DropXlsx.java:79)
    at java.awt.dnd.DropTarget.drop(DropTarget.java:455)
    at sun.awt.dnd.SunDropTargetContextPeer.processDropMessage(SunDropTargetContextPeer.java:538)
    at sun.awt.dnd.SunDropTargetContextPeer$EventDispatcher.dispatchDropEvent(SunDropTargetContextPeer.java:852)
    at sun.awt.dnd.SunDropTargetContextPeer$EventDispatcher.dispatchEvent(SunDropTargetContextPeer.java:776)
    at sun.awt.dnd.SunDropTargetEvent.dispatch(SunDropTargetEvent.java:48)
    at java.awt.Component.dispatchEventImpl(Component.java:4744)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processDropTargetEvent(Container.java:4599)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4461)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
    Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections4.ListValuedMap
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 34 more

noclassdeffound implies that when executing there are missing dependencies that were present when compiling, but I don't understand what I should do in this case to solve it.

I must emphasize that I am getting this error when executing it directly from netbeans where it is supposed or I believe that I should compile the classes and libraries without any problem.

I thank you in advance for any help you can offer me.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
ramej
  • 15
  • 6
  • 1
    Are you running your code from an IDE? Or are you running it from a _Command Prompt_ window? Or from a batch file or PowerShell script? – Abra Nov 14 '20 at 18:46
  • from the NetBeans IDE – ramej Nov 14 '20 at 18:56
  • 1
    `NoClassDefFoundError: org/apache/commons/collections4/ListValuedMap`: You are missing the [Commons Collections](https://commons.apache.org/proper/commons-collections/download_collections.cgi) v4 library (jar file). I recommend using a dependency manager such as Maven, Gradle, etc, as these tools will handle the required dependencies for you - for example, for the core [POI dependencies](https://mvnrepository.com/artifact/org.apache.poi/poi/4.1.2). This [question](https://stackoverflow.com/questions/4270950/compile-time-vs-run-time-dependency-java) may also be useful as background reading. – andrewJames Nov 14 '20 at 21:06
  • ok, I am going to approve the maven manager, I thought that when executing it from netbeans I would have no problem with dependencies besides that I have added all the libraries. – ramej Nov 19 '20 at 21:18

0 Answers0