Excel文檔導出和導入

2 Excel文檔導出
response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));

2.1  


3 Excel文檔導入
3.1  
界面:
var htmlStr = "";
    htmlStr += '<div style="width:600px;" >';   
    htmlStr += '<div style="display:block; padding-bottom:20px;" align="center" >';
    htmlStr += '<form  id = "userExcelFileFormId" action="/SSMPro/uploadExcel" method="post" >';
    htmlStr += '<input type="file" id="userExcelFile" name="userExcelFile"  onchange="ValidateFileType()" >';
    htmlStr += ' <input type="submit"  value="導入"  />  ';
    htmlStr += '</form>';
    htmlStr += '</table>';
    htmlStr += '</div>';
    htmlStr += '</div>';

    $.layer({
        type : 1,
        title : '導入用戶',
        area : [ 'auto', 'auto' ],
        page : {
            html : htmlStr
        }
    });


function ValidateFileType() {
    var array = new Array();
    // 得到上傳的Excel表格的名稱
    var excelName = $("#userExcelFile").val();
    // 拆分
    array = excelName.split(".");
    var suffix = array[array.length - 1];
    if (suffix != "xlsx" && suffix != "xls") {
        alert("您選擇的不是excel文檔,請重新選擇");
        var file = document.getElementById("userExcelFile");
        file.value = "";
    }
}

/**
 * 使用ajax提交表單,要引入jquryForm的js文件
 */
function submitFrom() {
    var options = {
        beforeSubmit : showRequest,
        success : showResponse,
        resetForm : true,
        dataType : 'json'
    };

    $("#userExcelFileFormId").submit(function() {
        $(this).ajaxSubmit(options);

        return false;
    });
}

function showRequest(){

}

function showResponse(responseText) {
    if (responseText.isSuccess == true) {
        alert('導入成功');
        window.location = "/SSMProject/user/userMana";
    }
}

@RequestMapping("/uploadExcel")
    public void uploadExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            // 把request對象轉換成Spring的request對象
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 獲取上傳的文件列表
            Map<String, MultipartFile> fileMap = multiRequest.getFileMap();
            // 遍歷
            for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
                // 獲取上傳的excel文件
                MultipartFile file = entry.getValue();
                // 得到文件輸入流
                InputStream inputStream = file.getInputStream();
                // 創建excel文檔對象
                Workbook workbook = WorkbookFactory.create(inputStream);
                // 讀取文檔的內容
                List<Map<String, Object>> list = this.readExcel(workbook);
                // 把讀取到的內容插入到數據庫中
                userService.insertData(list);
                // 返回標識
                resultMap.put("isSuccess", true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("isSuccess", false);
        }

        Gson gson = new Gson();
        String responseContent = gson.toJson(resultMap);
        this.flushResponse(response, responseContent);
    }

    /**
     * 讀取sheet中的內容
     * @param workbook
     * @return
     */
    private List<Map<String, Object>> readExcel(Workbook workbook) {
        // 得到SimpleReadParameter對象,封裝了插入的字段名和讀取文檔的下標
        SimpleReadParameter srp = this.getSimpleReadParameter();
        String[] fieldNames = srp.getFieldsId();
        int startIndex = srp.getStartIndex();

        ExcelUtil excelUtil = new ExcelUtil();
        List<Map<String, Object>> list = new ArrayList<>();
        // 判斷是否有工作單元
        if (workbook != null && workbook.getNumberOfSheets() > 0) {
            // 得到sheet對象
            Sheet sheet = workbook.getSheetAt(0);
            // 通過工具類來讀取sheet中的內容
            List<Map<String, Object>> sheetData = excelUtil.readSimple(sheet, startIndex, fieldNames);
            if (sheetData != null && sheetData.size() > 0) {
                list.addAll(sheetData);
            }
        }
        return list;
    }

    /**
     * 得到要插入到數據庫的字段名和起始下標
     * 
     * @return
     */
    private SimpleReadParameter getSimpleReadParameter() {
        SimpleReadParameter simpleReadParameter = new SimpleReadParameter();

        StringBuffer sbBuffer = new StringBuffer();
        sbBuffer.append("userChName,").append("mobilePhone,").append("email,").append("userSex,").append("userName,")
                .append("orgId,");

        String[] filedNames = sbBuffer.toString().split(",");
        int startIndex = 2;
        simpleReadParameter.setFieldsId(filedNames);
        simpleReadParameter.setStartIndex(startIndex);
        return simpleReadParameter;
    }

}

導出
@RequestMapping("/exportUserExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = "";
        // 獲取傳過來的參數
        Map<String, Object> param = this.getParam(request);
        Object fileNameObj = param.get("fileName");

        // 創建一個默認的日期來拼接文件名
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String defaultDate = sdf.format(date);

        if (fileNameObj != null && !("").equals(fileNameObj.toString())) {
            String fileChName = fileNameObj.toString();
            // 截取文件名
            if (fileChName.endsWith(".xls") || fileChName.endsWith(".xlsx")) {
                fileChName = fileChName.substring(0, fileChName.lastIndexOf("."));
            }
            fileName = fileChName + defaultDate;
        } else {
            fileName = defaultDate;
        }
        // 統一確定後綴
        fileName = fileName + ".xls";

        OutputStream outputStream = null;
        try {
            // 得到一個輸出流
            outputStream = response.getOutputStream();

            // 創建一個excel文檔對象
            Workbook wb = new HSSFWorkbook();
            // 設置響應頭
            // Content-Disposition 的作用,當Content-Type 的類型爲要下載的類型時 ,
            // 這個信息頭會告訴瀏覽器這個文件的名字或類型。
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
            // Excel導出操作
            this.exprotUserExcel(wb);
            // 把文檔對象輸出
            wb.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
            if (outputStream != null) {
                outputStream.close();

            }
        }

    }

    // Excel導出操作
    private void exprotUserExcel(Workbook wb) {
        // 得到輸入excel文檔數據的對象
        SimpleExportParameter parameters = this.getSimpleExportParamter();
        // 創建sheet對象
        Sheet sheet = wb.createSheet();
        ExcelUtil util = new ExcelUtil();
        // 填充excel文檔內容
        util.simpleExport(wb, sheet, parameters);
    }

    //填充SimpleExportParameter對象
    private SimpleExportParameter getSimpleExportParamter() {
        // 從數據庫查出的屬性要與下面的屬性對應(用“,”分隔,先後順序與數據庫查出結果的順序一致)
        String filedIds = "userChName,userSex,mobilePhone,provinceName,cityName,contryName,userBirthday";
        // 中文名稱
        String filedName = "姓名,性別,電話,省份,地市,區縣,生日";
        // 列寬
        String widthsStr = "20,20,20,20,20,20,20";

        // 從數據庫中查詢數據
        List<Map<String, Object>> dataList = userService.queryExprotData();

        // 設置標題
        String title = "千鋒員工信息";
        // 設置sheet名稱
        String sheetName = "員工sheet";

        String[] ids = filedIds.split(",");
        String[] names = filedName.split(",");
        String[] widths = widthsStr.split(",");

        // 給對象賦值
        SimpleExportParameter sep = new SimpleExportParameter();
        sep.setTitle(title);
        sep.setTitleEn(sheetName);
        sep.setFieldsId(ids);
        sep.setFieldsName(names);
        sep.setWidths(widths);
        sep.setDataList(dataList);
        return sep;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章