上传 excel 文件以在 Jtable 上显示后出现参数类型不匹配错误(Eclipse - Java Swing)

Argument type mismatch error after uploading excel file to display on Jtable (Eclipse - Java Swing)

这个项目有三个 .java 文件。 Product.java; ExcelHelper.java; JFrameImpor.java 运行应用程序后,它会要求您导入 excel(.xls) 文件,然后打开一个选项卡,显示 "Argument type mismatch"

Product.java

package entities;
import java.util.*;
public class Product {

    private String id;
    private String name;
    private long price;     
    private int quatity;
    private boolean status;
    private Date creationDate;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public long getPrice() {
        return price;
    }
    public void setPrice(long price) {
        this.price = price;
    }
    public int getQuatity() {
        return quatity;
    }
    public void setQuatity(int quatity) {
        this.quatity = quatity;
    }
    public boolean isStatus() {
        return status;
    }
    public void setStatus(boolean status) {
        this.status = status;
    }
    public Date getCreationDate() {
        return creationDate;
    }
    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
    public Product(String id, String name, long price, int quatity, boolean status, Date creationDate) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
        this.quatity = quatity;
        this.status = status;
        this.creationDate = creationDate;
    }
    public Product() {
        super();
    }
}

ExcelHelper.java

package helper;

import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;

public class ExcelHelper {

    public List<String> fieldNames = new ArrayList<String>();
    private Workbook workbook = null;
    private String workbookName = "";

    public ExcelHelper(String workbookName){
        this.workbookName = workbookName;
        initialize();

    }

    private void initialize() {
        setWorkbook(new HSSFWorkbook());

    }

    public void closeWorksheet(){
        FileOutputStream fileOut;
        try{
            fileOut = new FileOutputStream(getWorkbookName());
            getWorkbook().write(fileOut);
            fileOut.close();            
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    private boolean setupFieldsForClass(Class<?> clazz) throws Exception{
        Field[] fields = clazz.getDeclaredFields();
        for(int i=0; i < fields.length ; i++){
            fieldNames.add(fields[i].getName());
        }
        return true;
    }

    private Sheet getSheetWithName(String name){
        Sheet sheet = null;
        for(int i=0; i < workbook.getNumberOfSheets() ; i++){
            if(name.compareTo(workbook.getSheetName(i)) == 0){
                sheet = workbook.getSheetAt(i);
                break;
            }
        }
        return sheet;
    }

    private void initializeForRead() throws InvalidFormatException, IOException{
        InputStream inp = new FileInputStream(getWorkbookName());
        workbook = WorkbookFactory.create(inp);
        }

    @SuppressWarnings({"unchecked", "rawtypes"})

    public <T> List<T> readData(String classname) throws Exception{
        initializeForRead();
        Sheet sheet = getSheetWithName(classname);
        Class clazz = Class.forName(workbook.getSheetName(0));
        setupFieldsForClass(clazz);
        List<T> result = new ArrayList<T>();
        Row row;
        for(int rowCount=1; rowCount<3; rowCount++){
            T one = (T) clazz.newInstance();
            row = sheet.getRow(rowCount);
            int colCount = 0;
            result.add(one);
            for(Cell cell : row){
                CellType type = cell.getCellTypeEnum();
                String fieldName = fieldNames.get(colCount++);
                Method method = constructMethod(clazz, fieldName);
                if(type ==  CellType.STRING ){
                    String value = cell.getStringCellValue();
                    Object[] values = new Object[1];
                    values[0] = value;
                    method.invoke(one,  values);
                } else if(type==  CellType.NUMERIC){
                    Double num = cell.getNumericCellValue();
                            Class<?>returnType = getGetterReturnClass(clazz, fieldName);
                            if(returnType == int.class || returnType == Integer.class){
                                method.invoke(one, num.intValue());
                            }else if(returnType == double.class || returnType == Double.class){
                                method.invoke(one, num);
                            }else if(returnType == float.class || returnType == Float.class){
                                method.invoke(one, num.floatValue());
                            }else if(returnType == long.class || returnType == Long.class){
                                method.invoke(one, num.longValue());
                            }else if(returnType == Date.class ){
                                Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
                                method.invoke(one, date);
                            }
                            }else if (type == CellType.BOOLEAN){
                                boolean num1 = cell.getBooleanCellValue();
                                Object[] values = new Object[1];
                                values[0] = num1;
                                method.invoke(one, values);
                            }
                }
            }

            return result;
        }


    private Class<?> getGetterReturnClass(Class<?> clazz, String fieldName) {
        String methodName = "get" + capitalize(fieldName);
        String methodIsName = "is" + capitalize(fieldName);
        Class<?> returnType = null;
        for(Method method : clazz.getMethods()){
            if(method.getName().equals(methodName)|| method.getName().equals(methodIsName)){
                returnType = method.getReturnType();
                break;
            }
        }
        return returnType;
    }
    @SuppressWarnings({"unchecked", "rawtypes"})
    private Method constructMethod(Class clazz, String fieldName) throws SecurityException, NoSuchMethodException {
        Class<?> fieldClass = getGetterReturnClass(clazz, fieldName);
        return clazz.getMethod("set" + capitalize(fieldName), fieldClass );
    }

    public <T> void writeData(List<T> data) throws Exception {
       try{
        Sheet sheet = getWorkbook().createSheet(data.get(0).getClass().getName());
        setupFieldsForClass(data.get(0).getClass());
        int rowCount = 0;
        int columnCount = 0;
        Row row = sheet.createRow(rowCount++);
        for (String fieldName : fieldNames) {
            Cell cel = row.createCell(columnCount++);
            cel.setCellValue(fieldName);            
        }
        Class<? extends Object> classz = data.get(0).getClass();
        for (T t : data) {
            row = sheet.createRow(rowCount++);
            columnCount = 0;
            for (String fieldName : fieldNames) {
                Cell cel = row.createCell(columnCount);
                Method method = hasMethod(classz, fieldName)
                        ? classz.getMethod("get"+ capitalize(fieldName))
                        : classz.getMethod("is"+ capitalize(fieldName));
                Object value = method.invoke(t, (Object[]) null);
                if (value != null) {
                    if (value instanceof String) {
                        cel.setCellValue((String) value);
                    } else if (value instanceof Long) {
                        cel.setCellValue((Long) value);
                    } else if (value instanceof Integer) {
                        cel.setCellValue((Integer) value);
                    } else if (value instanceof Double) {
                        cel.setCellValue((Double) value);
                    }else if (value instanceof Date){
                        cel.setCellValue((Date) value);
                        CellStyle styleDate = workbook.createCellStyle();
                        DataFormat dataFormatDate = workbook.createDataFormat();
                        styleDate.setDataFormat(dataFormatDate.getFormat("m/d/yy"));
                        cel.setCellStyle(styleDate);
                    }else if (value instanceof Boolean){
                        cel.setCellValue((Boolean) value);
                    }
                }
                columnCount++;
            }
        }

        for(int i=0 ; i< fieldNames.size(); i++)
            sheet.autoSizeColumn(i);

            FileOutputStream out = new FileOutputStream(new File(workbookName));
            workbook.write(out);
            out.close();
            workbook.close();
        }catch (Exception e){
            System.out.println("Error:" + e);
        }
       }

    @SuppressWarnings({"unchecked", "rawtypes"})

    private boolean hasMethod(Class classz, String fieldName) {
        try{
            classz.getMethod("get" + capitalize(fieldName));
            return true;
        } catch (Exception e){
            return false;
        }
    }

    public String capitalize(String string) {
        String capital = string.substring(0,1).toUpperCase();
        return capital + string.substring(1);
    }
    public String getWorkbookName() {
        return workbookName;

    }
    public void setWorkbookName(String workbookName) {
        this.workbookName = workbookName;
    }

    void  setWorkbook(Workbook workbook) {
        this.workbook =  workbook;
    }
    public Workbook getWorkbook(){
         return workbook;
     }


}

JFrameImpor.java

package main;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

import com.ibm.icu.text.SimpleDateFormat;

import entities.Product;
import helper.ExcelHelper;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JButton;
import javax.swing.JFileChooser;

import java.awt.event.ActionListener;
import java.util.List;
import java.awt.event.ActionEvent;

public class JFrameImpor extends JFrame {

    private JPanel contentPane;
    private JTable tableProducts;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JFrameImpor frame = new JFrameImpor();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public JFrameImpor() {
        setTitle("Import Excel File");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(5, 5, 424, 2);
        contentPane.add(scrollPane);

        tableProducts = new JTable();
        tableProducts.setBounds(20, 11, 393, 174);
        contentPane.add(tableProducts);

        JButton btnImport = new JButton("Import");
        btnImport.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser jf = new JFileChooser();
                jf.setDialogTitle("Please select an excel file to import");
                int result = jf.showOpenDialog(null);
                if(result==JFileChooser.APPROVE_OPTION){
                    String excelPath = jf.getSelectedFile().getAbsolutePath();
                    ExcelHelper eh = new ExcelHelper(excelPath);
                    try{
                        List<Product> listProduct = eh.readData(Product.class.getName());
                        DefaultTableModel dtm = new DefaultTableModel();
                        dtm.addColumn("Id");
                        dtm.addColumn("Name");
                        dtm.addColumn("Price");
                        dtm.addColumn("Quantity");
                        dtm.addColumn("Status");
                        dtm.addColumn("Creation Date");
                        SimpleDateFormat sdf = new  SimpleDateFormat("yyyy-MM-dd");
                        for(Product p : listProduct){
                            dtm.addRow(new Object[] {p.getId(), p.getName(), p.getPrice(), p.getQuatity(), p.isStatus(), sdf.format(p.getCreationDate()) });
                        }
                        tableProducts.setModel(dtm);

                    }catch(Exception e){
                        JOptionPane.showMessageDialog(null, e.getMessage());
                    }


                    //JOptionPane.showMessageDialog(null, excelPath);
                }
            }
        });
        btnImport.setBounds(20, 196, 89, 23);
        contentPane.add(btnImport);
            }
}

它没有显示任何错误,但是当您 运行 应用程序在上传文件后显示参数类型不匹配。

Image 1 description : That is how the window builder of the project looks like.

我发现如果您提供的输入与预期的输入类型不同,程序会抛出 IllegalArgumentException。 示例输入应如下所示:-

id name    price   quatity status  creationDate 
1  test    10.51   20      TRUE    2016-05-05

输入类型应与产品 class 的 getter/setter 方法类型完全匹配。