首页 > 代码库 > 导出功能的实现

导出功能的实现

10.导出

a.在网页上新建一个导出按钮

<a onclick="toExport()" class="easyui-linkbutton" iconCls="icon-export">导出</a>

b.JavaScript中写按钮的触发事件

//获取参数
function getJsonParams(){
    var searchName = encodeURI($("#ss").textbox("getValue"));
    var json={name:searchName,depid:depid};
   return json2str(json)
}
//导出
function toExport() {
    var paramJsonStr = getJsonParams();
    window.location.href = "ProjectExcelExport?systemname=student&type=StuQuery?ms=" + paramJsonStr;
}

值得注意的是:该向后台发送的请求并不是hebe请求,而是servlet请求,因此在请求控制配置不在gatewaybeans.xml中,而是在web.xml

c.web.xml中配置请求控制

<!--excel导出-->
<servlet>
    <servlet-name>ProjectExcelExport</servlet-name>
    <servlet-class>cn.com.goldsea.hebedemo.entity.ProjectExcelExport</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ProjectExcelExport</servlet-name>
    <url-pattern>/ProjectExcelExport</url-pattern>
</servlet-mapping>

值得注意的是:该配置文件路径点击能找到该类

d.选一个地方新建一个类ProjectExcelExport

public class ProjectExcelExport extends HttpServlet{
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.reset();

        String systemname = request.getParameter("systemname");
        String type = request.getParameter("type");
        String params = request.getParameter("params");
        String fileName = "";
        HSSFWorkbook workbook = new HSSFWorkbook();

        //学生查询
        if (systemname.equals("student")) {
            StudentExcelBean bean = new StudentExcelBean();
            Object[] obj = bean.landStudentExcel(type, params, workbook);
            fileName = (String) obj[0];
            workbook = (HSSFWorkbook) obj[1];
        }
值得注意的是:所有导出其他地方都一样,需要改变的就是这里,根据发送的参数不同选择相应的判断条件

        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");     //firefox浏览器
        } else {
            fileName = encode(fileName, "UTF-8");        //IE浏览器
        }
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".xls" + "\"");
        ServletOutputStream sos = null;
        try {
            sos = response.getOutputStream();
            workbook.write(sos);
            sos.flush();
        } finally {
            try {
                sos.close();
            } catch (IOException e) {
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * 替换字符串卷
     *
     * @param str     被替换的字符串
     * @param charset 字符集
     * @return 替换好的
     * @throws java.io.UnsupportedEncodingException 不支持的字符集
     */
    public static String encode(String str, String charset) throws UnsupportedEncodingException {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]+");      //只替换中文汉字
        Matcher m = p.matcher(str);
        StringBuffer b = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(b, URLEncoder.encode(m.group(0), charset));
        }
        m.appendTail(b);
        return b.toString();
    }
}

e.在需要导出相关的bean包下面新建一个Excel包,在该包下面新建一个StudentExcelBean

该类用于需要导出表的查询或表格名的设置,当然还是需要建一个工具类ExcelUtils

 技术分享

public class StudentExcelBean extends BaseBean{
    public Object[] landStudentExcel(String type, String params, HSSFWorkbook workbook) {
        String xlsName = "";
        if (type.equals("StuQuery")) {
            xlsName = "学生信息一览表";
            List<Map<String, Object>> maps = getStuQueryExcelData(params);
            if (null != maps) {
                StuQueryExcel excel = new StuQueryExcel();
                workbook = excel.getStuQueryExcel(workbook, maps, xlsName);
            }
        }
        return new Object[]{xlsName, workbook};
    }
    private List<Map<String, Object>> getStuQueryExcelData(String param) {

        String name = JSON_UTIL.getJsonData(param, "name");
        String depid=JSON_UTIL.getJsonData(param,"depid");
        String sql=  "select s.sno,s.name,s.birthday,s.createtime,s.sex,s.depid,s.loginname,d.depname "+
                "from t_student s, t_department d where s.depid = d.id"  ;
        if(name!=null&&!name.equals("")){
            sql += " and s.name like ‘%" + name + "%‘";
        }
        if(depid!=null&&!depid.equals("")){
            sql += " and s.depid=" + depid;
        }
        sql += " order by d.id";
        return DBL_CLIENT.invokeQuery(sql);
    }
}

值得注意的是:该类基本上都是需要自己写的。其中这个sql语句拼接就是查询时后台bean中的sql语句。即可以根据条件查询后再导出自己需要的列表

 

f.Excel包中再新建一个StuQueryExcel类,该类用于设置导出成Excel表的属性

 

public class StuQueryExcel {
    public HSSFWorkbook getStuQueryExcel(HSSFWorkbook workbook, List<Map<String, Object>> maps, String xlsName) {
        HSSFCellStyle cellStyleNormal = workbook.createCellStyle();
        cellStyleNormal.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        cellStyleNormal.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        cellStyleNormal.setWrapText(true);

        HSSFSheet sheet = workbook.createSheet(xlsName);

        //设置列宽
        sheet.setColumnWidth(0, 3000);
        sheet.setColumnWidth(1, 4000);
        sheet.setColumnWidth(2, 4000);
        sheet.setColumnWidth(3, 4000);
        sheet.setColumnWidth(4, 3000);
        sheet.setColumnWidth(5, 5000);

        HSSFRow row = sheet.createRow(0);
        sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) 5));
        HSSFCell cell = row.createCell((short) 0);
        HSSFFont font = workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font.setFontHeightInPoints((short) 18);
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(font);
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(new HSSFRichTextString(xlsName));

        row = sheet.createRow(1);
        row.setHeight((short) 400);
        ExcelUtils.GenerateNormalCell(new CellRangeAddress(1, 1, 0, 0), 0, "学号", sheet, cellStyleNormal, row);
        ExcelUtils.GenerateNormalCell(new CellRangeAddress(1, 1, 1, 1), 1, "姓名", sheet, cellStyleNormal, row);
        ExcelUtils.GenerateNormalCell(new CellRangeAddress(1, 1, 2, 2), 2, "生日", sheet, cellStyleNormal, row);
        ExcelUtils.GenerateNormalCell(new CellRangeAddress(1, 1, 3, 3), 3, "创建时间", sheet, cellStyleNormal, row);
        ExcelUtils.GenerateNormalCell(new CellRangeAddress(1, 1, 4, 4), 4, "性别", sheet, cellStyleNormal, row);
        ExcelUtils.GenerateNormalCell(new CellRangeAddress(1, 1, 5, 5), 5, "所属院系", sheet, cellStyleNormal, row);

        int rowIndex = 2;
        Object[] objects;
        for (Map<String, Object> objectMap : maps) {
            row = sheet.createRow(rowIndex);
            row.setHeight((short) 400);
            objects = new Object[6];
            objects[0] = objectMap.get("sno") != null ? objectMap.get("sno").toString() : "";
            objects[1] = objectMap.get("name") != null ? objectMap.get("name").toString() : "";
            if (objectMap.get("birthday") != null) {
                objects[2] = DateUtil.time2(Long.valueOf(String.valueOf(objectMap.get("birthday")).substring(0, 8)));
            } else {
                objects[2] = "";
            }
            if (objectMap.get("createtime") != null) {
                objects[3] = DateUtil.time2(Long.valueOf(String.valueOf(objectMap.get("createtime")).substring(0, 8)));
            } else {
                objects[3] = "";
            }
            if (String.valueOf(objectMap.get("sex")).equals("1")) {
                objects[4] = "男";
            }  else {
                objects[4] = "女";
            }

            objects[5] = objectMap.get("depname") != null ? objectMap.get("depname").toString() : "";

            loadContractRow(objects, rowIndex, sheet, cellStyleNormal, row);
            rowIndex++;
        }
        return workbook;
    }

    private void loadContractRow(Object[] objects, int rowIndex, Sheet sheet, HSSFCellStyle cellStyleNormal, HSSFRow row) {
        int count = 0;
        if (null != objects && objects.length > 0) {
            for (int i = 0; i < objects.length; i++) {
                ExcelUtils.GenerateNormalCell(new CellRangeAddress(rowIndex, rowIndex, count, count), count, objects[i], sheet, cellStyleNormal, row);
                count++;
            }
        }
    }
}

值得注意的是:标蓝的地方都是需要自己写的,根据默认列表字段来写

导出功能的实现