导入数据后如何使用数组

时间:2014-05-05 13:10:24

标签: java excel import analysis

正在开发一个从Excel导入的程序,然后我想将导入的数字放入数组中。那么我将做一些计算,比如特定数组的总和,两个数组的乘积。 如何将导入的数字作为数组读取,然后进行计算?

这是代码。

package csvfile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 * @author Christine
 */
public class CsvFrame extends javax.swing.JFrame {

    /**
     * Creates new form CsvFrame
     */
    public CsvFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jMenuBar2 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        scrollPane = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jMenuBar1 = new javax.swing.JMenuBar();
        menuFile = new javax.swing.JMenu();
        menuOpen = new javax.swing.JMenuItem();
        menuSave = new javax.swing.JMenuItem();
        menuExit = new javax.swing.JMenuItem();

        jMenu1.setText("File");
        jMenuBar2.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar2.add(jMenu2);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null}
                },
                new String[]{
                        "Title 1", "Title 2", "Title 3", "Title 4"
                }
        ));
        scrollPane.setViewportView(jTable1);

        menuFile.setText("File");

        menuOpen.setText("Open");
        menuOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuOpenActionPerformed(evt);
            }
        });
        menuFile.add(menuOpen);

        menuSave.setText("Save");
        menuSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuSaveActionPerformed(evt);
            }
        });
        menuFile.add(menuSave);

        menuExit.setText("Exit");
        menuExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuExitActionPerformed(evt);
            }
        });
        menuFile.add(menuExit);

        jMenuBar1.add(menuFile);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(20, 20, 20)
                                .addComponent(scrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 
                                        489, javax.swing.GroupLayout.PREFERRED_SIZE)

                                .addContainerGap(23, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
                                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    String location;

    private void menuSaveActionPerformed(java.awt.event.ActionEvent evt) {
        String line = "";
        int y = 0, z = 0;// y- column, z - row
        try {

            location = JOptionPane.showInputDialog("Please Enter A Location");

            FileWriter writer = new FileWriter(location);
            while (z < jTable1.getRowCount() - 1) {

                if (z == 0) {// titles
                    while (y < jTable1.getColumnCount()) {
                        // writes the values separated by commas    as long as ts not the end of column
                        if (y < jTable1.getColumnCount() - 1) { 
                            line = line + jTable1.getColumnName(y) + ",";
                        } else {
                            line = line + jTable1.getColumnName(y);
                        } // writes the last value of   the column without a comma afta t
                        y++;
                    }
                } else {

                    while (y < jTable1.getColumnCount()) {
                        if (y < jTable1.getColumnCount() - 1) {
                            line = line + jTable1.getValueAt(z - 1, y).toString() + ",";
                        } else {
                            line = line + jTable1.getValueAt(z - 1, y).toString();
                        }
                        y++;
                    }
                }
                line = line + "\n";

                writer.write(line);
                line = "";
                y = 0;
                z++;
            }

            writer.close();
        } catch (IOException ex) {

        }


        // TODO add your handling code here:
        //        JFileChooser chooser = new JFileChooser();
        //       File f = chooser.s
    }

    private void menuOpenActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:

        // indtsntiating an object of   type model coz its the type taken in by the table
        DefaultTableModel model = new DefaultTableModel();
        jTable1.setModel(model);// set the created object the table
        JFileChooser jfc = new JFileChooser();
        ArrayList<Integer> xValue = new ArrayList<Integer>();
        ArrayList<Integer> yValue = new ArrayList<Integer>();
        ArrayList<Integer> zValue = new ArrayList<Integer>();
        jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        int i = jfc.showOpenDialog(jfc);

        if (i == JFileChooser.CANCEL_OPTION) {
            jfc.cancelSelection();
        }

        if (i == JFileChooser.APPROVE_OPTION) {
            File file = jfc.getSelectedFile();

            try {
                BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath()));
                String line;// this string is going to be used to 
                int r = 0, c = 0;
                while ((line = br.readLine()) != null) {
                    model.addRow(new Object[]{""});//adds a row into the table.

                    //separating each word that z separated by commas and storing t in an array called value
                    String[] value = line.split(",");
                    while (c < value.length) {
                        if (r == 0) { //
                            model.addColumn(value[c]);
                        }
                        if (r != 0) {
                            jTable1.setValueAt(value[c], r - 1, c);
                            xValue.add(Integer.getInteger(value[0]));
                            yValue.add(Integer.getInteger(value[1]));
                            zValue.add(Integer.getInteger(value[2]));
                        }
                        c++;
                    }
                    c = 0;
                    r++;
                }

            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Error Openin File" + ex);
            }

        }

    }

    private void menuExitActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        this.dispose();
    }

    public void computemeant(int xValue[]) {
        double totalt = 0;
        for (int i = 0; i < xValue[]; i++) {
            totalt = totalt + xvalue[i];
        }
        double avgt = totalt / xValue[];
        return avgt;
    }


    /**
     * @param array
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code    (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see  http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        int xValue[] = new xValue[];
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CsvFrame.class.getName()).log(java.util.logging.Level.SE VERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CsvFrame.class.getName()).log(java.util.logging.Level.SE VERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CsvFrame.class.getName()).log(java.util.logging.Level.SE VERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CsvFrame.class.getName()).log(java.util.logging.Level.SE VERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */

        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new CsvFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JTable jTable1;
    private javax.swing.JMenuItem menuExit;
    private javax.swing.JMenu menuFile;
    private javax.swing.JMenuItem menuOpen;
    private javax.swing.JMenuItem menuSave;
    private javax.swing.JScrollPane scrollPane;
    // End of variables declaration                   
}

1 个答案:

答案 0 :(得分:0)

查看Apache POI,它能够读/写Microsoft文档(包括Excel电子表格)。通过简单的Google搜索在互联网上提供了大量示例,包括this onethis one