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     }

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM