zoukankan      html  css  js  c++  java
  • java中的excel数据的导入和导出

    Excel数据导出

    技术:Apache POI 是用Java编写的免费开源的跨平台的 Java APIApache POI提供APIJava程式对Microsoft Office格式档案读和写的功能。POI“Poor Obfuscation Implementation”的首字母缩写,意为可怜的模糊实现

    用它可以使用Java读取和创建,修改MS Excel文件.而且,还可以使用Java读取和创建MS WordMSPowerPoint文件。Apache POI 提供Java操作Excel解决方案(适用于Excel97-2008

    入门案例:

    思路: 1.导入依赖 2.测试

    1.1导入依赖

    1 <dependency>
    2           <groupId>org.apache.poi</groupId>
    3           <artifactId>poi</artifactId>
    4           <version>3.15</version>
    5       </dependency>

    1.2.测试,结果生成一张excel表格

    public static void main(String[] args) throws FileNotFoundException, IOException {
            // 创建excel
            HSSFWorkbook wk = new HSSFWorkbook();
            // 创建一张工作表
            HSSFSheet sheet = wk.createSheet();
            // 设置列宽
            sheet.setColumnWidth(0, 5000);
            // 创建第一行
            HSSFRow row = sheet.createRow(0);
            // 创建第一行的第一个单元格
            HSSFCell cell = row.createCell(0);
            // 想单元格写值
            cell.setCellValue("测试");
            // 保存到本地
            wk.write(new FileOutputStream(new File("D://ERP/a.xls")));
            // 关闭工作薄
            wk.close();
        }

    2.和项目的结合

    思路:1.依赖 2.service层 3.action层 4.web层

    2.1.依赖

    2.2.service层

    思路:
    1.创建工作薄
    2.工作表名字
    3.工作表创建
    4.创建行,创建每一个单元格
    5.给每个单元格塞数据
    6.关流
    

      

    /**
         * 导出供应商的数据
         */
        @Override
        public void export(OutputStream os, Supplier t1) {
            //查出符合条件的所供应/客户的列表
            List<Supplier> supplierList = supplierDao.getList(t1, null, null);
            //工作簿
            Workbook wk = new HSSFWorkbook();
    
            //创建工作表
            String sheetName = "";
            if(Supplier.TYPE_SUPPLIER.equals(t1.getType())){
                sheetName = "供应商";
            }
            if(Supplier.TYPE_CUSTOMER.equals(t1.getType())){
                sheetName = "客户";
            }
            Sheet sheet = wk.createSheet(sheetName);
            
            //创建一行,参数指的是: 行的索引=行号-1
            Row row = sheet.createRow(0);
            //列名,表头
            String[] headers = {"名称","地址","联系人","电话","Email"};
            //String[] methodname = {"getName","getAddress", "getContact","getTele","getEmail"};
            /*Method[] methods = Supplier.class.getMethods();
            Map<String, Method> methodNameMap = new HashMap<String,Method>();
            for(Method m : methods){
                methodNameMap.put(m.getName(), m);
            }*/
            for(int i = 0; i < headers.length; i++){
                row.createCell(i).setCellValue(headers[i]);
                
            }
            //创建单元格, 参数指的是:列的索引,从0开始
            //输出每一条记录
            if(null != supplierList && supplierList.size() > 0){
                Supplier supplier = null;
                for(int i = 1; i<=supplierList.size(); i++){
                    row = sheet.createRow(i);
                    supplier = supplierList.get(i-1);
                    /*for(String mname : methodname){
                        Method m = methodNameMap.get(mname);
                        try {
                            Object obj = m.invoke(supplier, new Object[]{});
                            Class<?> returnType = m.getReturnType();
                            //returnType.cast(obj);
                            row.createCell(0).setCellValue(returnType.cast(obj));//名称
                        } catch (IllegalAccessException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IllegalArgumentException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }*/
                    row.createCell(0).setCellValue(supplier.getName());//名称
                    row.createCell(1).setCellValue(supplier.getAddress());//地址
                    row.createCell(2).setCellValue(supplier.getContact());//联系
                    row.createCell(3).setCellValue(supplier.getTele());//电话
                    row.createCell(4).setCellValue(supplier.getEmail());//Email            
                }
            }
            
            //输出到输出流中
            try {
                wk.write(os);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    wk.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    2.3.action层

     1 思路:
     2 1.给下载的文件名字的判断
     3 2.设置下载的响应头
     4 /**
     5      * 导出
     6      */
     7     public void export(){
     8         try {
     9             String filename = "";
    10             if(Supplier.TYPE_SUPPLIER.equals(getT1().getType())){
    11                 filename = "供应商.xls";
    12             }
    13             if(Supplier.TYPE_CUSTOMER.equals(getT1().getType())){
    14                 filename = "客户.xls";
    15             }
    16             HttpServletResponse res = ServletActionContext.getResponse();
    17             res.setHeader("Content-Disposition", "attachment;filename=" +
    18                         new String(filename.getBytes(),"ISO-8859-1"));
    19             supplierBiz.export(ServletActionContext.getResponse().getOutputStream(),getT1());
    20         } catch (IOException e) {
    21             e.printStackTrace();
    22         }
    23     }

    2.4.前端

    思路:
    1.页面导入js
    2.js在抽取的crud中添加导出的按钮
    <script type="text/javascript" src="ui/download.js"></script>
    
    '-',{
                    text: '导出',
                    iconCls: 'icon-excel',
                    handler: function(){
                        //查询条件
                        var searchData = $('#searchForm').serializeJSON();
                        //请求下载文件
                        $.download("supplier_export?t1.type=" + Request['type'], searchData);
                    }
                },

     3.导出的进一步加强

    思路:1.依赖 2.service层创建创建表格和处理数据 3.action   4.前端

    1.依赖

    2.service层创建创建表格和处理数据

      1 //思路:1创建表格 2.sheet名字 3.数据样式 4.行数 5.数据处理6.关流
      2 /**
      3      * 导出订单
      4      */
      5     @Override
      6     public void exportById(OutputStream os, Long uuid) {
      7         //根据订单编号获取订单
      8         Orders orders = ordersDao.get(uuid);
      9         //订单明细
     10         List<Orderdetail> orderDetails = orders.getOrderDetails();
     11         
     12         String sheetName = "";
     13         if(Orders.TYPE_IN.equals(orders.getType())){
     14             sheetName = "采 购 单";
     15         }
     16         if(Orders.TYPE_OUT.equals(orders.getType())){
     17             sheetName = "销 售 单";
     18         }
     19         //工作簿
     20         HSSFWorkbook wk = new HSSFWorkbook();
     21 
     22         //创建工作表
     23         Sheet sheet = wk.createSheet(sheetName);
     24         
     25         //创建字体
     26         HSSFFont font_content = wk.createFont();
     27         font_content.setFontName("宋体");
     28         font_content.setFontHeightInPoints((short)12);
     29         
     30         //创建样式
     31         CellStyle style_content = wk.createCellStyle();
     32         //水平居中
     33         style_content.setAlignment(HorizontalAlignment.CENTER);
     34         //重直居中
     35         style_content.setVerticalAlignment(VerticalAlignment.CENTER);
     36         //设置字体
     37         style_content.setFont(font_content);
     38         
     39         //标题的样式, 样式克隆
     40         CellStyle style_title = wk.createCellStyle();
     41         style_title.cloneStyleFrom(style_content);
     42         HSSFFont font_title = wk.createFont();
     43         font_title.setFontName("黑体");
     44         font_title.setFontHeightInPoints((short)20);
     45         style_title.setFont(font_title);
     46         
     47         //设置边框
     48         style_content.setBorderBottom(BorderStyle.THIN);
     49         style_content.setBorderLeft(BorderStyle.THIN);
     50         style_content.setBorderRight(BorderStyle.THIN);
     51         style_content.setBorderTop(BorderStyle.THIN);
     52         
     53         //日期样式
     54         HSSFCellStyle style_date = wk.createCellStyle();
     55         style_date.cloneStyleFrom(style_content);
     56         HSSFDataFormat dataFormat = wk.createDataFormat();
     57         style_date.setDataFormat(dataFormat.getFormat("yyyy-MM-dd hh:mm"));
     58         
     59         
     60         //创建一行,参数指的是: 行的索引=行号-1
     61         Row row = null;
     62         Cell cell = null;
     63         int rowCnt = 10 + orderDetails.size();
     64         for(int i = 2; i < rowCnt; i++){
     65             row = sheet.createRow(i);
     66             for(int j = 0; j < 4; j++){
     67                 cell = row.createCell(j);
     68                 //设置单元格样式
     69                 cell.setCellStyle(style_content);
     70             }
     71         }
     72         //设置日期格式
     73         sheet.getRow(3).getCell(1).setCellStyle(style_date);
     74         sheet.getRow(4).getCell(1).setCellStyle(style_date);
     75         sheet.getRow(5).getCell(1).setCellStyle(style_date);
     76         sheet.getRow(6).getCell(1).setCellStyle(style_date);
     77         //sheet.getRow(3).getCell(1).setCellValue(new Date());
     78         
     79         //合并单元格,订单名称
     80         sheet.addMergedRegion(new CellRangeAddress(0,0,0,3));
     81         //供应商名称
     82         sheet.addMergedRegion(new CellRangeAddress(2,2,1,3));
     83         //明细
     84         sheet.addMergedRegion(new CellRangeAddress(7,7,0,3));
     85         
     86         //设置header内容
     87         Cell title_cell = sheet.createRow(0).createCell(0);
     88         title_cell.setCellStyle(style_title);
     89         title_cell.setCellValue("采 购 单");
     90         sheet.getRow(2).getCell(0).setCellValue("供应商");
     91         
     92         //日期 与 人
     93         row = sheet.getRow(3);
     94         row.getCell(0).setCellValue("下单日期");
     95         row.getCell(2).setCellValue("经办人");
     96         row = sheet.getRow(4);
     97         row.getCell(0).setCellValue("审核日期");
     98         row.getCell(2).setCellValue("经办人");
     99         row = sheet.getRow(5);
    100         row.getCell(0).setCellValue("采购日期");
    101         row.getCell(2).setCellValue("经办人");
    102         row = sheet.getRow(6);
    103         row.getCell(0).setCellValue("入库日期");
    104         row.getCell(2).setCellValue("经办人");
    105         
    106         sheet.getRow(7).getCell(0).setCellValue("订单明细");
    107         
    108         row = sheet.getRow(8);
    109         row.getCell(0).setCellValue("商品名称");
    110         row.getCell(1).setCellValue("数量");
    111         row.getCell(2).setCellValue("价格");
    112         row.getCell(3).setCellValue("金额");
    113         //设置行高与列宽
    114         //调整行的高度
    115         sheet.getRow(0).setHeight((short)1000);
    116         for(int i = 2; i < rowCnt; i++){
    117             sheet.getRow(i).setHeight((short)500);
    118         }
    119         //调整列宽
    120         for(int i = 0; i < 4; i++){
    121             sheet.setColumnWidth(i, 5000);
    122         }
    123         //写入订单详情
    124         sheet.getRow(2).getCell(1).setCellValue(supplierDao.getName(orders.getSupplieruuid()));
    125         if(null != orders.getCreatetime()){//下单日期
    126             sheet.getRow(3).getCell(1).setCellValue(orders.getCreatetime());
    127         }
    128         if(null != orders.getChecktime()){//审核日期
    129             sheet.getRow(4).getCell(1).setCellValue(orders.getChecktime());
    130         }
    131         if(null != orders.getStarttime()){//采购日期
    132             sheet.getRow(5).getCell(1).setCellValue(orders.getStarttime());
    133         }
    134         if(null != orders.getEndtime()){//入库日期
    135             sheet.getRow(6).getCell(1).setCellValue(orders.getEndtime());
    136         }
    137         //经办人
    138         sheet.getRow(3).getCell(3).setCellValue(empDao.getName(orders.getCreater()));
    139         sheet.getRow(4).getCell(3).setCellValue(empDao.getName(orders.getChecker()));
    140         sheet.getRow(5).getCell(3).setCellValue(empDao.getName(orders.getStarter()));
    141         sheet.getRow(6).getCell(3).setCellValue(empDao.getName(orders.getEnder()));
    142         
    143         //写入明细内容
    144         Orderdetail od = null;
    145         //rowCnt = 10+size - 9 = 1+size - 1=size
    146         for(int i = 9; i < rowCnt - 1; i++){
    147             od = orderDetails.get(i-9);
    148             row = sheet.getRow(i);
    149             row.getCell(0).setCellValue(od.getGoodsname());
    150             row.getCell(1).setCellValue(od.getNum());
    151             row.getCell(2).setCellValue(od.getPrice());
    152             row.getCell(3).setCellValue(od.getMoney());
    153         }
    154         //合计
    155         sheet.getRow(rowCnt - 1).getCell(0).setCellValue("合计");
    156         sheet.getRow(rowCnt - 1).getCell(3).setCellValue(orders.getTotalmoney());
    157         
    158         //输出到输出流中
    159         try {
    160             wk.write(os);
    161         } catch (IOException e) {
    162             e.printStackTrace();
    163         } finally{
    164             try {
    165                 wk.close();
    166             } catch (IOException e) {
    167                 e.printStackTrace();
    168             }
    169         }
    170     }
    171     

    3.action 

    //思路: 1.导出名字的设置,响应头 //2.service调用
    /**
         * 导出订单
         */
        public void exportById(){
            try {
                String filename = String.format("orders_%d.xls", getId());//"orders_" + getId() + ".xls";
                HttpServletResponse res = ServletActionContext.getResponse();
                res.setHeader("Content-Disposition", "attachment;filename=" +
                            new String(filename.getBytes(),"ISO-8859-1"));
                ordersBiz.exportById(ServletActionContext.getResponse().getOutputStream(),getId());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    4.前端

     1 //1.在html 页面导入js 2.在 orders.js中(弹出的dialog中要有导出) 添加导出后按钮
     2 <script type="text/javascript" src="ui/download.js"></script>
     3 var ordersDlgToolbar = new Array();
     4     //添加审核的按钮
     5     if(Request['oper'] == 'doCheck'){
     6         ordersDlgToolbar.push({text:'审核',iconCls:'icon-search',handler:doCheck});
     7         
     8     }
     9     //添加确认的按钮
    10     if(Request['oper'] == 'doStart'){
    11         ordersDlgToolbar.push({text:'确认',iconCls:'icon-search',handler:doStart});
    12     }
    13     //导出
    14     ordersDlgToolbar.push({text:'导出',iconCls:'icon-excel',handler:function(){
    15         $.download("orders_exportById", {id:$('#uuid').html()});
    16     }});
    17     //如果有按钮,就把加到窗口里去
    18     if(ordersDlgToolbar.length > 0){
    19         $('#ordersDlg').dialog({
    20             toolbar:ordersDlgToolbar
    21         });
    22     }

      

  • 相关阅读:
    gdb调试工具
    一步步理解Linux之中断和异常
    英语感受 5月份英语思维
    2013年6月4日星期二
    2013年5月29日星期三
    2013年6月3日星期一
    第22周六晚上
    2013年5月26日星期日
    2013年5月28日20:16:21
    2013年6月2日星期日
  • 原文地址:https://www.cnblogs.com/liushisaonian/p/7098125.html
Copyright © 2011-2022 走看看