JAVA導出Excel(支持多sheet)


 

一、批量導出:

/**
     * 
     * @Title: expExcel 
     * @Description: 批量導出客戶信息
     * @param @param params
     * @param @param request
     * @param @param response
     * @param @throws Exception
     * @return void
     * @throws
     */
    @RequestMapping("expExcel")
    public void expExcel(QueryCustomParam params,HttpServletRequest request,HttpServletResponse response) throws Exception{
        
        User u = getUser(request.getSession());//SessionUtils.getUser(request.getSession());
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        
        //獲取網站部署路徑(通過ServletContext對象),用於確定下載文件位置,從而實現下載  
        String path = request.getServletContext().getRealPath("/");  
        
        List<CustomResp> list = null;
        List<ContactsResp> list2 = null;
        String fileName = "我的客戶導出";
        String url = path + "download\\" + fileName + ".xls";
        
        params.setEmpIds(String.valueOf(u.getEmpId()));
        QueryContactsParam params2 = new QueryContactsParam();
        params2.setEmpId(Long.valueOf(u.getEmpId()));
        params2.setCorpId(Long.valueOf(u.getCorpId()));
        params2.setFlag("4");
        
        try {  
            
            list = customService.selectMyCustom(params); //我的客戶
            list2 = contactsService.selectContactsList(params2); //查詢我的客戶包含的所有聯系人信息
            
            //數據
            List<String[]> dataset = new ArrayList<String[]>();
            for (int i = 0; i < list.size(); i++) {
                String[] arr = new String[16];
                arr[0] = list.get(i).getName()==null ? "" : list.get(i).getName().toString(); 
                arr[1] = list.get(i).getShortName()==null ? "" : list.get(i).getShortName().toString();
                arr[2] = list.get(i).getNumber()==null ? "" : list.get(i).getNumber().toString();
                arr[3] = list.get(i).getAddress()==null ? "" : list.get(i).getAddress().toString();
                arr[4] = list.get(i).getUrl()==null ? "" : list.get(i).getUrl().toString();
                arr[5] = list.get(i).getDescription()==null ? "" : list.get(i).getDescription().toString();
                arr[6] = list.get(i).getHighseasName()==null ? "" : list.get(i).getHighseasName().toString();
                arr[7] = list.get(i).getHighseasDate()==null ? "" : sdf2.format(list.get(i).getHighseasDate());
                arr[8] = list.get(i).getEmpName()==null ? "" : list.get(i).getEmpName().toString();
                arr[9] = list.get(i).getOrganName()==null ? "" : list.get(i).getOrganName().toString();
                arr[10] = ""; //領取日期    暫無數據
                arr[11] = list.get(i).getExpireDate()==null ? "" : sdf2.format(list.get(i).getExpireDate());
                arr[12] = "4"; //聯系人數量
                arr[13] = list.get(i).getCreateDate()==null ? "" : sdf2.format(list.get(i).getCreateDate());
                arr[14] = list.get(i).getCustomStatusName()==null ? "" : list.get(i).getCustomStatusName().toString();
                arr[15] = list.get(i).getCustomLevelName()==null ? "" : list.get(i).getCustomLevelName().toString();
                
                dataset.add(arr);
            }
            
            //數據
            List<String[]> dataset2 = new ArrayList<String[]>();
            for (int i = 0; i < list2.size(); i++) {
                String[] arr2 = new String[16];
                arr2[0] = list2.get(i).getName()==null ? "" : list2.get(i).getName().toString(); 
                arr2[1] = list2.get(i).getSex()==null ? "" : getSex(list2.get(i).getSex());
                arr2[2] = list2.get(i).getBirthday()==null ? "" : sdf.format(list2.get(i).getBirthday());
                arr2[3] = "";
                arr2[4] = list2.get(i).getOrganName()==null ? "" : list2.get(i).getOrganName().toString();
                arr2[5] = list2.get(i).getPosition()==null ? "" : list2.get(i).getPosition().toString();
                arr2[6] = list2.get(i).getCompany()==null ? "" : list2.get(i).getCompany().toString();
                arr2[7] = list2.get(i).getAddress()==null ? "" : list2.get(i).getAddress().toString();
                arr2[8] = list2.get(i).getUrl()==null ? "" : list2.get(i).getUrl().toString();
                arr2[9] = list2.get(i).getInterest()==null ? "" : list2.get(i).getInterest().toString(); 
                arr2[10] = list2.get(i).getRemark()==null ? "" : list2.get(i).getRemark().toString();
                arr2[11] = list2.get(i).getCreateDate()==null ? "" : sdf2.format(list2.get(i).getCreateDate()); 
                arr2[12] = list2.get(i).getCustomName()==null? "" : list2.get(i).getCustomName();
                arr2[13] = list2.get(i).getEmpName()==null? "" : list2.get(i).getEmpName();
                arr2[14] = list2.get(i).getContactsRoleName()==null? "" : list2.get(i).getContactsRoleName();
                arr2[15] = list2.get(i).getContactsRelationName()==null? "" : list2.get(i).getContactsRelationName();
                
                dataset2.add(arr2);
            }
            
            //表頭
            String[] handers1 = {"客戶全稱","客戶簡稱","客戶編號","地址","網址","介紹","公海名稱","加入公海時間","跟進人","跟進人部門","領取日期","到期日期","聯系人數量","創建日期","客戶狀態","客戶分級" };
            String[] handers2 = {"姓名","性別","生日","手機","部門","職務","公司","公司地址","公司網站","興趣愛好","備注","創建日期","客戶簡稱","歸屬人","角色關系","親密程度" };
            
            //對象
            ExcelExp e1 = new ExcelExp("我的客戶", handers1, dataset);
            ExcelExp e2 = new ExcelExp("客戶聯系人", handers2, dataset2);
            
            List<ExcelExp> mysheet = new ArrayList<ExcelExp>();
            mysheet.add(e1);
            mysheet.add(e2);
            
            ExcelExportUtil.exportManySheetExcel(url, mysheet); //生成sheet
            ExcelExportUtil.getExcel(url, fileName, response); //下載sheet
            
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }
    

Excel對象:

public class ExcelExp {
    
    private String fileName;// sheet的名稱
    private String[] handers;// sheet里的標題
    private List<String[]> dataset;// sheet里的數據集

    public ExcelExp(String fileName, String[] handers, List<String[]> dataset) {
        this.fileName = fileName;
        this.handers = handers;
        this.dataset = dataset;
    }

    //getter、setter方法

}

生成Excel:

/**
     * 
     * @Title: exportManySheetExcel 
     * @Description: 可生成單個、多個sheet 
     * @param @param file 導出文件路徑
     * @param @param mysheets
     * @return void
     * @throws
     */
    public static void exportManySheetExcel(String file, List<ExcelExp> mysheets){
        
        HSSFWorkbook wb = new HSSFWorkbook();//創建工作薄
        List<ExcelExp> sheets = mysheets;
        
        //表頭樣式
        HSSFCellStyle style = wb.createCellStyle();  
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創建一個居中格式  
        //字體樣式
        HSSFFont fontStyle = wb.createFont();    
        fontStyle.setFontName("微軟雅黑");    
        fontStyle.setFontHeightInPoints((short)12);    
        fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 
        style.setFont(fontStyle);
        
        for(ExcelExp excel: sheets){
            //新建一個sheet
            HSSFSheet sheet = wb.createSheet(excel.getFileName());//獲取該sheet名稱
            
            String[] handers = excel.getHanders();//獲取sheet的標題名
            HSSFRow rowFirst = sheet.createRow(0);//第一個sheet的第一行為標題
            //寫標題
            for(int i=0;i<handers.length;i++){
                //獲取第一行的每個單元格
                HSSFCell cell = rowFirst.createCell(i);
                //往單元格里寫數據
                cell.setCellValue(handers[i]);
                cell.setCellStyle(style); //加樣式
                sheet.setColumnWidth(i, 4000); //設置每列的列寬
            }
            
            //寫數據集
            List<String[]> dataset = excel.getDataset();
            for(int i=0;i<dataset.size();i++){
                String[] data = dataset.get(i);//獲取該對象
                
                //創建數據行
                HSSFRow row = sheet.createRow(i+1);
                
                for(int j=0;j<data.length;j++){
                    //設置對應單元格的值
                    row.createCell(j).setCellValue(data[j]);
                }
            }
        }
        
        // 寫文件
        try {
            
            FileOutputStream out = new FileOutputStream(new File(file));
            out.flush();  
            wb.write(out);    
            out.close(); 
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

 


免責聲明!

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



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