POI Excel導入導出

一.導出到Exceljavascript

   基本思路:點擊導出後生成臨時.xls文件,返回文件名,供用戶下載,下載完後刪除文件html

   帶查詢的導出(前端EasyUI),以下爲導出界面圖前端

  

  下面爲導出按鈕綁定的函數:java

var exportCondition={};//導出條件
//導出功能 function outputData(){ $.ajax({ type: "POST", url: path+"/main/inputAndOutput/output", data: exportCondition, success: function (fileName) { var downUrl = path+"/main/inputAndOutput/download?fileName=" + fileName; window.location = downUrl; } }); }

   //查詢功能
   function search(){
     //按條件進行查詢數據,首先咱們獲得數據的值
     //獲得用戶輸入的參數,取值有幾種方式:$("#id").combobox('getValue'), $("#id").datebox('getValue'), $("#id").val()
       //字段增長search_前綴字符,避免傳遞如URL這樣的Request關鍵字衝突
       var queryData = {
           search_type: $("#search_type").combobox('getValue'),
           search_address: $("#search_address").combotree("tree").tree("getSelected")!=null?$("#search_address").combotree("tree").tree("getSelected").id:"",
           search_name: $("#search_name").textbox('getValue'),
           search_year: $("#search_year").textbox('getValue'),
           search_publicType: $("#search_publicType").textbox('getValue'),
           search_publicName: $("#search_publicName").textbox('getValue'),
           search_layout: $("#search_layout").combobox('getValue'),
           search_status: $("#search_status").combobox('getValue')
       }
       //將值傳遞給
       initGrid(queryData);
       
       //將查詢條件傳遞給導出
       exportCondition = queryData;
   }

 

後臺:生成.xls文件,返回文件名web

@RequestMapping(value="output",method=RequestMethod.POST)
    @ResponseBody
    public String output(HttpServletRequest request,HttpServletResponse response){
        Map<String, Object> param = new HashMap<String, Object>();
        List<YellowPagesResourceModel> list = new ArrayList<YellowPagesResourceModel>();
        String fileName="";
        try {
            
            //獲取查詢條件
            param = getQueryParam(request);
            
            list = this.yellowpageResService.QueryAllForGridData(param);
            if(list.size()>0){
                //建立webbook,對應一個Excel文件
                HSSFWorkbook wb = new HSSFWorkbook();
                
                //設置表頭及樣式
                HSSFSheet sheet = defineHeader(wb);
                
                //填充數據
                writeData(list, sheet);
                
                //數據寫入文件
                fileName=writeToFile(wb);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

/**
     * 設置表頭和樣式
     * @param wb
     * @return
     */
    private HSSFSheet defineHeader(HSSFWorkbook wb) {
        //添加sheet,對應Excel文件中sheet
        HSSFSheet sheet = wb.createSheet("黃頁資源(一)");
        
        //建立表頭
        HSSFRow row = sheet.createRow(0);
        
        //建立單元格,設置表頭值
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//居中格式
        
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("序號");
        cell.setCellStyle(style);
        
        cell = row.createCell(1);
        cell.setCellValue("所屬地市");
        cell.setCellStyle(style);
        
        cell = row.createCell(2);
        cell.setCellValue("地區");
        cell.setCellStyle(style);
        
        cell = row.createCell(3);
        cell.setCellValue("年份");
        cell.setCellStyle(style);
        
        cell = row.createCell(4);
        cell.setCellValue("書名");
        cell.setCellStyle(style);
        
        cell = row.createCell(5);
        cell.setCellValue("刊式代碼");
        cell.setCellStyle(style);
        
        cell = row.createCell(6);
        cell.setCellValue("刊式名稱");
        cell.setCellStyle(style);
        
        cell = row.createCell(7);
        cell.setCellValue("刊式尺寸");
        cell.setCellStyle(style);
        
        cell = row.createCell(8);
        cell.setCellValue("價格");
        cell.setCellStyle(style);
        
        cell = row.createCell(9);
        cell.setCellValue("版面");
        cell.setCellStyle(style);
        return sheet;
    }

    /**
     * 寫入數據到excel
     * @param list
     * @param sheet
     */
    private void writeData(List<YellowPagesResourceModel> list, HSSFSheet sheet) {
        HSSFRow row = null;
        //寫入數據
        YellowPagesResourceModel model = null;
        for(int i=0;i<list.size();i++){
            row = sheet.createRow(i+1);
            model = list.get(i);
            row.createCell(0).setCellValue(i+1);
            row.createCell(1).setCellValue(model.getAddress());
            row.createCell(2).setCellValue(model.getAddressStr());
            row.createCell(3).setCellValue(model.getPagesYear());
            row.createCell(4).setCellValue(model.getPagesName());
            row.createCell(5).setCellValue(model.getPublicCode());
            row.createCell(6).setCellValue(model.getPublicName());
            row.createCell(7).setCellValue(model.getPublicType());
            row.createCell(8).setCellValue(model.getPrice().toString());
            row.createCell(9).setCellValue(model.getLayout()==1?"普通版面":"特殊版面");
        }
    }

    /**
     * 數據寫入磁盤文件
     * @param wb
     * @throws IOException
     * @throws FileNotFoundException
     */
    private String writeToFile(HSSFWorkbook wb) throws IOException,
            FileNotFoundException {
        // 讀取配置文件獲取實際保存路徑
        Properties props = PropertiesLoaderUtils.loadAllProperties("otherCfg.properties");
        //實際保存路徑
        String saveDir = props.getProperty("PathToYellowPagesResFile_DEV");
        File fileDir = new File(saveDir.toString());
        if(!fileDir.exists()){
            fileDir.mkdirs();
        }
        String fileName = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "-" +RandomUtils.nextInt();
        String filePath = saveDir+File.separator+fileName+".xls";
        FileOutputStream fout = new FileOutputStream(filePath);
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        wb.write(ostream);
        fout.write(ostream.toByteArray());
        fout.flush();
        ostream.close();
        fout.close();
        return fileName+".xls";
    }

文件下載在此就很少提,注意的是在下載完後記得刪除上面生成的.xls文件,其次爲了解決亂碼,以下設置responseajax

/**
     * 解決附件下載名稱亂碼
     * @param request
     * @param response
     * @param params
     * @throws UnsupportedEncodingException
     */
    private void solveGarbled(HttpServletRequest request,
                                HttpServletResponse response,
                                Map<String, String> params
                                ) throws UnsupportedEncodingException{
        if (request.getHeader("User-Agent").toLowerCase().indexOf("msie") > -1){//IE瀏覽器
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(params.get("realFileName"), "iso-8859-1"));
        }else if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > -1){//firefox瀏覽器
            response.setContentType("application/x-xls");
            response.addHeader("content-disposition", "attachment;filename=\"" + params.get("realFileName") + "\"");
        }else{//其餘瀏覽器
            response.setContentType("application/x-xls");
            response.addHeader("content-disposition", "attachment;filename=" + params.get("realFileName"));
        }
    }

導出.xls文件以下:數據庫

  

 

二.xls導入數據到數據庫apache

   基本思路:上傳.xls,轉換成.csv,讀取數據,存入數據庫api

   導入對話框以下所示:瀏覽器

  

以下爲代碼:

 <div id="inputDlg" class="easyui-dialog" style="width:380px;height:220px;"
             data-options="buttons: '#inputDlg-buttons',closed:true,modal: true">
                 <form id="uploadForm"  method="post" enctype="multipart/form-data">  
                     <table cellpadding="8">
                        <tr class="fitem">
                                <td>
                                    <input id="uploadExcel" name="uploadExcel" class="easyui-filebox" style="width:250px;"
                                        data-options="prompt:'請選擇.xls文件...'">  
                                </td>
                        </tr>
                        <tr class="fitem">
                             <td>
                                 <label>黃頁類型:</label><input id="uploadType" name="uploadType" class="easyui-combobox"/>
                             </td>
                        </tr>
                     </table>
                </form> 
                <p style="color:red;font-size:12px;text-align:center;">請注意導入的Excel數據字段和
                    <a href="${pageContext.request.contextPath}/main/inputAndOutput/downloadTemplate">Excel模板</a>一致
                </p>
    </div>
    <div id="inputDlg-buttons">
            <a href="javascript:void(0)" class="easyui-linkbutton"
                data-options="iconCls:'icon-save'" onclick="uploadFile()">上傳</a> 
           <a id="uploadBtn" href="javascript:void(0)" class="easyui-linkbutton"
                data-options="iconCls:'icon-cancel'"
                onclick="javascript:$('#inputDlg').dialog('close')">取消</a>
    </div>
//文件上傳
function uploadFile(){
    //獲得文件路徑
    var filePath = $('#uploadExcel').filebox('getValue');
    if(filePath!=""){
        //對文件格式進行驗證(簡單驗證)
        var d1=/\.[^\.]+$/.exec(filePath);
        if(d1==".xls"){
            $('#uploadForm').form('submit',{
                   url: path+'/main/inputAndOutput/upload',
                   success: function(data){
                       if (data){
                           $('#inputDlg').dialog('close');
                           $("#grid").datagrid('reload');
                       } else {
                           $.messager.alert('操做提示',"導入失敗,請檢查數據是否正確!",'error');
                       }
                   }
               });
        }else{
            $.messager.alert('舒適提示','請選擇.xls文件!','warning');
        }
    }else{
        $.messager.alert('舒適提示','請選擇.xls文件!','warning');
    }
}

後臺:

  

    @RequestMapping(value="upload")
    @ResponseBody
    public String upload(HttpServletRequest request,HttpServletResponse response) throws IOException{
        String result=null;
        //文件上傳到磁盤
        Map<String,String> map = uploadExcel(request);
        
        String fileName = map.get("fileName");
        Integer type =Integer.parseInt(map.get("type"));
        List<String> dataList = new ArrayList<String>();
        Properties props = PropertiesLoaderUtils.loadAllProperties("otherCfg.properties");
        String saveDir = props.getProperty("PathToYellowPagesResFile_DEV");
        String filePath = saveDir+File.separator+fileName;
        try {
            
            //.xls轉換爲.csv
            XLS2CSVmra xls2csv = new XLS2CSVmra(filePath+".xls", filePath+".csv");
            xls2csv.process();
            //刪除.xls
            File file = new File(filePath+".xls");
            if(file.exists())file.delete();
            
            //獲取.csv中數據
            File csvFile = new File(filePath+".csv"); 
            dataList = CSVUtils.importCsv(csvFile);
            
            //刪除.csv
            csvFile.delete();
            for(String s:dataList){
                System.out.println(s);
            }
            
            if(dataList.size()>0){
                //.csv中數據轉換爲entity
                List<YellowPagesResource> instances = new ArrayList<YellowPagesResource>();
                instances = convertToEntity(type, dataList);
                //保存至數據庫
                this.yellowpageResService.createOrModify(instances);
                result = "成功導入:"+instances.size()+"條數據.";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

說明:

  (1).xls轉換爲.csv,因爲.csv以一行數據的字符串並用「,」分隔存放數據,因此能夠實現一行一行地讀取數據

      apache官方的例子:實現.xls-->.csv和.xlsx--->.csv
  XLS2CSV: http://www.docjar.com/html/api/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java.html
  XLSX2CSV: https://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/eventusermodel/XLSX2CSV.java

  (2)獲取.csv的數據(注意設置編碼集,不然容易亂碼)

public static List<String> importCsv(File file){
        List<String> dataList=new ArrayList<String>();
        FileInputStream in = null;
        BufferedReader br=null;
        try { 
            in = new FileInputStream(file);
            br = new BufferedReader(new InputStreamReader(in, "GBK"));//設置編碼集
            String line = ""; 
            while ((line = br.readLine()) != null) { 
                dataList.add(line);
            }
        }catch (Exception e) {
        }finally{
            if(br!=null){
                try {
                    br.close();
                    br=null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
 
        return dataList;
    }

(3).csv中數據轉換爲entity

    /**
     * 將從csv中獲取的數據轉換成Entity
     * @param type 資源類型
     * @param dataList
     */
    private List<YellowPagesResource> convertToEntity(Integer type, List<String> dataList) {
        String[] cells = null;
        List<YellowPagesResource> instances = new ArrayList<YellowPagesResource>();
        for(int i=0;i<dataList.size();i++){
            cells = dataList.get(i).replace("\"", "").split(",");
            if(cells.length<10){
                continue;
            }else{
                YellowPagesResource ypr = new YellowPagesResource();
                ypr.setPagesName(cells[4]);
                ypr.setPagesYear(cells[3]);
                ypr.setAddress(cells[1]);
                ypr.setPublicCode(cells[5]);
                ypr.setPublicName(cells[6]);
                ypr.setPublicType(cells[7]);
                ypr.setStatus(2);//未銷售
                ypr.setCreator(SecurityUserHolder.getCurrentUser().getName());
                ypr.setProductId("402881ea4c5e43fd014c60660ffd0000");//這個暫時寫死的
                ypr.setType(type);
                if("特殊版面".equals(cells[9])){
                    ypr.setLayout(2);
                }else if("普通版面".equals(cells[9])){
                    ypr.setLayout(1);
                }else{
                    continue;
                }
                ypr.setPrice(BigDecimal.valueOf(Double.parseDouble(cells[8])));
                instances.add(ypr);
            }
        }
        return instances;
    }

注:以上實例未給出驗證上傳的.xls數據格式是否合法,只是在轉換爲entity時簡單判斷了(這樣是不行的!)

相關文章
相關標籤/搜索