当前位置: 代码迷 >> Java相关 >> java swing jtable 自定义导出
  详细解决方案

java swing jtable 自定义导出

热度:863   发布时间:2013-10-08 11:51:04.0
java swing jtable 自定义导出
整理了一下jtable自定义导出
-----------------------------------
package test;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.table.*;
public class ExeclExporter  {
    public ExeclExporter() { }

    public void exportTable(JTable table, File file) throws IOException {
        TableModel model = table.getModel();
        BufferedWriter bWriter = new BufferedWriter(new FileWriter(file));
        for(int i=0; i < model.getColumnCount(); i++) {
            bWriter.write(model.getColumnName(i));
            bWriter.write("\t");
        }
        bWriter.newLine();
        for(int i=0; i< model.getRowCount(); i++) {
            for(int j=0; j < model.getColumnCount(); j++) {
                bWriter.write(model.getValueAt(i,j).toString());
                bWriter.write("\t");
            }
            bWriter.newLine();
        }
        bWriter.close();
        System.out.println("write out to: " + file);
    }
   
    public static void main(String[] args) {
        String[][] data = {
            { "Housewares",  "$1275.00" },
            { "Pets",         "$125.00" },
            { "Electronics", "$2533.00" },
            { "Mensware",     "$497.00" }
        };
        String[] headers = { "Department", "Daily Revenue" };

        final JFrame frame = new JFrame("JTable to Excel Hack");
        DefaultTableModel model = new DefaultTableModel(data,headers);
        final JTable table = new JTable(model);
        JScrollPane scroll = new JScrollPane(table);

        JButton export = new JButton("Export");
        export.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                   // TODO add your handling code here:导出
                FileDialog fd = new FileDialog(frame, "保存流水记录", FileDialog.SAVE);
                fd.setLocation(400, 250);
                fd.setVisible(true);
                String stringfile = fd.getDirectory()+fd.getFile()+".xls";
                   try {
                       ExeclExporter oDao = new ExeclExporter();
                    oDao.exportTable(table, new File(stringfile));
                   } catch (IOException ex) {
                       System.out.println(ex.getMessage());
                       ex.printStackTrace();
                   }   
            }
        });

        frame.getContentPane().add("Center",scroll);
        frame.getContentPane().add("South",export);
        frame.pack();
        frame.setVisible(true);
    }
}

搜索更多相关的解决方案: package  public  import  java  file  

----------------解决方案--------------------------------------------------------
ExeclExporter oDao = new ExeclExporter();这个需要引入什么包呢?
----------------解决方案--------------------------------------------------------
  相关解决方案