zoukankan      html  css  js  c++  java
  • Swing表格数据转xls文档

    花了一下午的时间终于实现了Swing表格数据转xls文档与读取xls文档数据。

    接下来上代码

    1.弹出保存xls文件目录选择框

    exportBtn.addActionListener(new ActionListener() {
                
                @Override
                public void actionPerformed(ActionEvent e) {
                    String name = "数据.xls";
                    String defaultPath = "D://temp";
                  //构造文件保存对话框
                    JFileChooser chooser = new JFileChooser();
                    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
                    chooser.setMultiSelectionEnabled(false);
                    chooser.setAcceptAllFileFilterUsed(false);
                    chooser.setDialogTitle("保存数据文件");
                    
                    //设置默认路径
                    File defaultFile = new File(defaultPath+"//data");
                    if(!defaultFile.exists()){
                        defaultFile.mkdirs();
                    }
                    chooser.setCurrentDirectory(new File(defaultPath));
                    //打开对话框
                    int result = chooser.showSaveDialog(getWindow());//null
                    
                    //文件确定 
                    if(result==JFileChooser.APPROVE_OPTION) {
                        String outPath = chooser.getSelectedFile().getAbsolutePath();
                        File f = new File(outPath);
                        if(f.isDirectory()) {
                            outPath = outPath+"\"+name;
                        }
                        if(new File(outPath).exists()){
                            int b = DialogUtils.showYesNoOptionDialog(getWindow(), "文件已经存在,是否要覆盖该文件?","操作确认");
                            if(b!=0){
                                return;
                            }
                        }
                        
                        File file = new File(outPath);
                        ExcelExporter ee = new ExcelExporter();
                        try {
                            ee.exportTable(xTable, file);
                        } catch (IOException e1) {
                            new RuntimeException(e1);
                        }
                    }
                }
    
            });

    2.表格数据导出

    package net.doublecom.sdk.tool.wirelessinfo.view;
    
    import java.io.*;
    import org.freeabc.client.core.component.table.XTable;
    
    public class ExcelExporter  {  
        public ExcelExporter() { }  
        
        public void exportTable(XTable<?> xtable, File file) throws IOException {  //Xtable自定义组件,也可换成Jtable
         //
    TableModel tableModel = new JTable().getModel();
         // tableModel.getColumnCount()
    
            FileWriter out = new FileWriter(file);  
            
            for(int i=0; i < xtable.getColumnCount(); i++) {  
                if("名称.equals(xtable.getColumnName(i))||"年龄".equals(xtable.getColumnName(i)))
                out.write(xtable.getColumnName(i) + "	");  
            }  
            out.write("
    ");  
            for(int i=0; i< xtable.getRowCount(); i++) {  
                for(int j=0; j < xtable.getColumnCount(); j++) { 
                    if("名称".equals(xtable.getColumnName(j))||"年龄".equals(xtable.getColumnName(j)))
                        out.write(xtable.getValueAt(i,j).toString()+"	");  
                }  
                out.write("
    ");  
            }  
            out.close();  
            System.out.println("write out to: " + file);  
        }  
          
    } 

    3.读取xls文档数据

        importBtn.addActionListener(new ActionListener() {
                
                @Override
                public void actionPerformed(ActionEvent e) {
    
                    String defaultPath = "D://temp//data//";
                  //构造文件保存对话框
                    JFileChooser chooser = new JFileChooser();
                    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
                    chooser.setMultiSelectionEnabled(false);
                    chooser.setAcceptAllFileFilterUsed(false);
                    chooser.setDialogTitle("加载数据文件");
                    
                    //设置默认路径
                    File defaultFile = new File(defaultPath);
                    if(defaultFile.exists()){
                        chooser.setCurrentDirectory(new File(defaultPath));
                    }
                    //取得文件名输入框设置指定格式
                    chooser.addChoosableFileFilter(new FileFilter() {
                        @Override
                        public String getDescription() {
                            return "Excel文件(*.xls)";
                        }
                        @Override
                        public boolean accept(File f) {
                            if (f.getName().endsWith("xls") || f.isDirectory()) {
                                 return true; 
                            }else{
                                return false; 
                            }
                        }
                    });
                    //打开对话框
                    int result = chooser.showSaveDialog(getWindow());//null
                    //文件确定 
                    if(result==JFileChooser.APPROVE_OPTION) {
                        String outPath = chooser.getSelectedFile().getAbsolutePath();
                        File file = new File(outPath);
                        try {
                             StringBuffer sb = new StringBuffer();
                             List<String[]> dataArrs = new ArrayList<String[]>();
                             FileInputStream fis = new FileInputStream(file);
                             //InputStream is = fis.getInputStream();
                             BufferedReader reader = new BufferedReader(new InputStreamReader(fis,"gb2312"));
                             reader.readLine();//第一行信息,为标题信息,不用,如果需要,注释掉 
                             String line = null;  
                             while((line=reader.readLine())!=null){  
                                String item[] = line.split("\t");//xls格式文件为空格分隔符文件,这里根据逗号切分
                                if(item.length!=2)
                                continue;
                                dataArrs.add(item);
                             }  
                             for(String[] data:dataArrs) {
                                 if(data.length>=2) {
                                     sb.append("name="+data[0]);
                                     sb.append(" age="+data[1]+";");
                                 }
                             }
                          
                        reader.close();
                        } catch (IOException e1) {
                            new RuntimeException(e1);
                        }
                    }
                }
            });
  • 相关阅读:
    muduo源代码分析--Reactor在模型muduo使用(两)
    uinty3d导入错误问题解决
    道量化交易程序猿(25)--Cointrader之MarketData市场数据实体(12)
    CSS cursor 属性
    手动挖第一桶金,10日赚3十万元
    JavaScript取出字符串和尾随空格
    编程的子阵列和最大和膨胀的美(可连接的端到端)
    OpenCV图像的基础叠加
    [SCSS] Organize SCSS into Multiple Files with Partials
    [CSS Flex] Justify-content
  • 原文地址:https://www.cnblogs.com/free-discipline/p/11605841.html
Copyright © 2011-2022 走看看