• swing导出html到excel


     swing导出html到excel

     1  ShowCopDetal

    package com.product;
    
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Desktop;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridLayout;
    import java.awt.color.ColorSpace;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.awt.image.ColorConvertOp;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.URISyntaxException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    import javax.swing.AbstractAction;
    import javax.swing.AbstractButton;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComponent;
    import javax.swing.JEditorPane;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.ScrollPaneLayout;
    import javax.swing.SwingConstants;
    import javax.swing.UIManager;
    import javax.swing.WindowConstants;
    import javax.swing.event.HyperlinkEvent;
    import javax.swing.event.HyperlinkListener;
    import javax.swing.filechooser.FileFilter;
    
    import jxl.Workbook;
    import jxl.write.Label;
    import jxl.write.WritableCellFormat;
    import jxl.write.WritableFont;
    import jxl.write.WritableSheet;
    import jxl.write.WritableWorkbook;
    
    public class ShowCopDetal extends JPanel{
         // 内置了本地系统桌面操作支持
        private Desktop desktop;
    
        private static final long serialVersionUID = 1L;
    
        // html内容
       // private static final String HTML_TEXT = "<html><font color='red'><a href="http://www.helpsoff.com.cn" target="_blank">支持SOFF,插件无罪</a></font>";
        private static List contentheader;
        private static List contentbody;
        
        
       
    
        public static List getContentheader() {
            return contentheader;
        }
    
        public static void setContentheader(List contentheader) {
            ShowCopDetal.contentheader = contentheader;
        }
    
        public static List getContentbody() {
            return contentbody;
        }
    
        public static void setContentbody(List contentbody) {
            ShowCopDetal.contentbody = contentbody;
        }
    
        public ShowCopDetal() {}
    
       
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    //createGUI();                
                    scrollpanelinframe();
                }
            });
        }
    
        public static void createGUI() {
    
            JFrame frame = new JFrame("在Swing中使用Html标签");
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.setSize(new Dimension(450, 200));
    
            frame.getContentPane().add(new ShowCopDetal());
    
            frame.setResizable(false);
            frame.setLocationRelativeTo(null);
            
            frame.setAlwaysOnTop(true);
            frame.setVisible(true);
        }
       static  JFrame frame = new JFrame("model detail");
       
        /////////////////////////////////test/////////////////////////////////////
        public static void scrollpanelinframe() {
            
            //init data 
            testENT a=new testENT("zhangsan","23","china");
            testENT b=new testENT("lisi","26","usa");
            testENT c=new testENT("mhmd","28","my");
            
            testENT aa=new testENT("azhangsan","a23","china");
            testENT bb=new testENT("blisi","b26","usa");
            testENT cc=new testENT("cmhmd","c28","my");
            
            
            List ds=new ArrayList();
            ds.add(a);
            ds.add(b);
            ds.add(c);
            List ds2=new ArrayList();
            ds2.add(aa);
            ds2.add(bb);
            ds2.add(cc);
            List totalsds=new ArrayList();
            totalsds.add(ds);
            totalsds.add(ds2);
            
            ShowCopDetal.setContentbody(totalsds);
             
            String[] headerstr={"Colum 1","Colum 2","Colum 3","Colum 4"};         
            ShowCopDetal.setContentheader(java.util.Arrays.asList(headerstr));
            
             
            
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.setSize(new Dimension(1100, 760));
    
            StringBuffer initialText=new StringBuffer();
            initialText.append("<html>
    ");
            
            //initialText.append("<div style="border:2px solid ;">");
                   
            
            
            for(int v=0;v<totalsds.size();v++)
            {   
                
                initialText.append("<div style="border:10px solid orange;">");
                initialText.append("<fieldset>");
                initialText.append("<legend>{infomation of "+v+" }</legend>");
                initialText.append("<table >");
                initialText.append("<tr style="font-size:2px color:red"><td  colSpan="9">****************************************************************************************</td></tr>");
                       
                 for(int n=0;n<((List)totalsds.get(v)).size();n++)  
                 {
                     testENT te=(testENT) ((List)totalsds.get(v)).get(n);
                     
                     
                     initialText.append("<tr><td  colSpan="9">_______________"+te.getName()+"_________</td></tr>");
                      
                     initialText.append("<tr>");  
                     initialText.append("<td>");
                     initialText.append("<font size=+2 color=green>");                 
                     initialText.append(te.getName());
                     initialText.append("</font>");
                     initialText.append("</td>");
                     
                     
                     initialText.append("<td>");
                     initialText.append("<font size=+2 color=red>");                 
                     initialText.append(te.getAge());
                     initialText.append("</font>");
                     initialText.append("</td>");
                     
                     initialText.append("<td>");
                     initialText.append("<font size=+2 color=yellow>");                 
                     initialText.append(te.getCountry());
                     initialText.append("</font>");
                     initialText.append("</td>");
                     
                     initialText.append("</tr>");
                    // initialText.append("<tr><td  colSpan="9" style="border-bottom:#FF0000 solid 1px; 50%; background-color:#00CC33; text-align:center; line-height:24px;"></td></tr>");
                 
                 }             
                 initialText.append("</table>");
                 initialText.append("</fieldset>");
                 initialText.append("</div>");
                 
                  
            }
            System.out.println(initialText);
                 JButton btsave=new JButton("Save");
                 Dimension preferredSize = new Dimension(10,20);//设置尺寸
                 btsave.setPreferredSize(preferredSize);
                 btsave.setLocation(10, 10);
                 //btsave.addActionListener(this); 
                 btsave.addActionListener(new ActionListener() {
    
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        // TODO Auto-generated method stub
                          JOptionPane.showMessageDialog(null,"start");
                          //selectSavePath();
                        //List<String[]> list
                        //  getcontentbody();
                         // getcontentheader();
                                            
                          
                          List list=new ArrayList();
                          list.add(0,ShowCopDetal.getContentheader());
                          list.add(1,ShowCopDetal.getContentbody());
                          try {
                            writeExcel(list);
                        } catch (Exception e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                    }
                     
                     });
     
                
                 
                 //JPanel rightPanel=new JPanel();
                 JScrollPane rightPanel = new JScrollPane();
                 rightPanel.setLayout(new ScrollPaneLayout());
                
                 JLabel   theLabel = new JLabel(initialText.toString());
     
                   theLabel.setVerticalAlignment(SwingConstants.TOP);
                   theLabel.setHorizontalAlignment(SwingConstants.NORTH_EAST); 
                   theLabel.setLocation(100, 10);
                 
                 //JScrollPane.UPPER_LEFT_CORNER
                 rightPanel.setBorder(BorderFactory.createCompoundBorder(
                                 BorderFactory.createTitledBorder("preview detail"),
                                 BorderFactory.createEmptyBorder(40,10,20,20)));
               
                // rightPanel.setColumnHeaderView(btsave);
                 rightPanel.setRowHeaderView(btsave);
                 //rightPanel.setViewportView(btsave);
                  rightPanel.setViewportView(theLabel);
                  //rightPanel.setLayout(new ScrollPaneLayout());
                 
               //  frame.add(jscPanel); 
                  frame.add(rightPanel); 
          
            frame.setResizable(true);
            frame.setLocationRelativeTo(null);
           
            frame.setAlwaysOnTop(false);
            frame.setVisible(true);
        }
        
        public static void writeExcel(List list)
                   throws Exception {
                  //弹出保存框
                  JFileChooser file = ShowCopDetal.getFile();
                  //判断是否关闭或取消保存框
                  if (file != null) {
                   //的到保存路径
                   String fpath=file.getSelectedFile().getAbsolutePath()+".xls";
                   //创建文件
                   File f = new File(fpath);
                   WritableWorkbook wwb = Workbook.createWorkbook(new FileOutputStream(f));
                   WritableSheet ws = wwb.createSheet("TestSheet1", 0);
                   // 设置字体样式
                   WritableFont wfc = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD, false);
                   WritableCellFormat wcfFC = new WritableCellFormat(wfc);
                   // 遍历列头字段名
                   for (int i = 0; i < ((List)list.get(0)).size(); i++) {
                    Label labelC = new jxl.write.Label(i, 0, ((List)list.get(0)).get(i).toString(), wcfFC);
                    ws.addCell(labelC);
                   }
                   // 遍历内容
                   for (int i = 1; i < list.size(); i++) {
                    for (int j = 0; j < ((List)list.get(i)).size(); j++) {
                     Label labelC = new jxl.write.Label(j, i, ((List)list.get(i)).get(j).toString());
                      
                     ws.addCell(labelC);
                    }
                   }
                   // 写入Exel工作表
                   wwb.write();
                   // 关闭Excel工作薄对象
                   wwb.close();
                   //消息框
                   JOptionPane.showMessageDialog(null, "File is saved to:"+fpath,"Save success!",JOptionPane.INFORMATION_MESSAGE);
                  }
                 }
        
        public static JFileChooser getFile() {
              //默认打开D盘
              JFileChooser file = new MyChooser("");
              // 下面这句是去掉显示所有文件这个过滤器。
              file.setAcceptAllFileFilterUsed(false);
              // 添加excel文件的过滤器
              file.addChoosableFileFilter(new ExcelFileFilter("xls"));
              int result = file.showSaveDialog(null);
              // JFileChooser.APPROVE_OPTION是个整型常量,代表0。就是说当返回0的值我们才执行相关操作,否则什么也不做。
              if (result == JFileChooser.APPROVE_OPTION) {
               // 获得你选择的文件绝对路径。并输出。当然,我们获得这个路径后还可以做很多的事。
               String path = file.getSelectedFile().getAbsolutePath();
               System.out.println(path);
              } else {
               file = null;
               System.out.println("You have canceled and colosed the window!");
              }
              return file;
             }
             //文件过滤器 只保存xls文件
             private static class ExcelFileFilter extends FileFilter {
              String ext;
              ExcelFileFilter(String ext) {
               this.ext = ext;
              }
              @Override
              public boolean accept(File f) {
               if (f.isDirectory()) {
                return true;
               }
               String fileName = f.getName();
               int index = fileName.lastIndexOf('.');
               if (index > 0 && index < fileName.length() - 1) {
                String extension = fileName.substring(index + 1).toLowerCase();
                if (extension.equals(ext))
                 return true;
               }
               return false;
              }
              @Override
              public String getDescription() {
               if (ext.equals("xls")) {
                return "Microsoft Excel file(*.xls)";
               }
               return "";
              }
             }
        
        private static class MyChooser extends JFileChooser {
         
              private static final long serialVersionUID = 1L;
              MyChooser(String path) {
               super(path);
              }
              public void approveSelection() {
               File file = this.getSelectedFile();
               if (file.exists()) {
                int copy = JOptionPane.showConfirmDialog(null, "Do you want to overwrite the current file?",
                  "Save", JOptionPane.YES_NO_OPTION,
                  JOptionPane.QUESTION_MESSAGE);
                if (copy == JOptionPane.YES_OPTION)
                 super.approveSelection();
               } else
                super.approveSelection();
              }
             }
        
    }

    2 bean 类

    package com.product;
    
    public class testENT {
    
        public testENT (String name,String age,String country)
        {
            this.name=name;
            this.age=age;
            this.country=country;
        }
        private String name;
        private String age;
        private String country;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getAge() {
            return age;
        }
        public void setAge(String age) {
            this.age = age;
        }
        public String getCountry() {
            return country;
        }
        public void setCountry(String country) {
            this.country = country;
        }
        
        
        
    }

    3 依赖jar   :

       jxl-2.4.2.jar

    4 截图:

  • 相关阅读:
    HDU 2669 Romantic【扩展欧几里德】
    POJ 1061 青蛙的约会【扩展欧几里德】
    求逆元
    扩展欧几里德算法
    HDU 3400 Line belt【三分套三分】
    HDU 2298 Toxophily 【二分+三分】
    006服务监控看板Hystrix Dashboard
    005hystrix.stream信息聚合Turbine
    003客户端负载均衡Ribbon & 短路器Hystrix
    004声明式服务调用Feign & 断路器Hystrix
  • 原文地址:https://www.cnblogs.com/rojas/p/4218873.html
Copyright © 2020-2023  润新知