Execl导出

1、ExeclUtil.java

public class ExcelUtil {
    public static <T> HSSFWorkbook exprotExcel(String title, String[] headers, String[] getMethods, List<T> dataset) {

        HSSFWorkbook workbook = new HSSFWorkbook();

        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);

        // 设置表格默认列宽为15字节
        sheet.setDefaultColumnWidth(15);

        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 背景色
        style.setFillForegroundColor(HSSFColor.WHITE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        // 边框
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);

        // 自动换行
        style.setWrapText(true);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.BLACK.index);// 字色
        font.setFontHeightInPoints((short) 10);// 字号
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示
        font.setFontName("宋体");
        // 把字体 应用到当前样式
        style.setFont(font);

        // 居中显示
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        // 生成另一个样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        // 背景色
        style2.setFillForegroundColor(HSSFColor.WHITE.index);
        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        // 边框
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 居中显示
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 文本显示位置
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 自动换行
        style2.setWrapText(true);
        // 生成一个字体
        HSSFFont font2 = workbook.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示
        // 把字体 应用到当前样式
        style2.setFont(font2);

        // 声明一个画图的顶级管理器
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        // 定义注释的大小和位置
        HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
        // 设置注释内容
        comment.setString(new HSSFRichTextString("可以在poi中添加注释"));
        // 设置注释作责,当鼠标移动到单元格上可以在状态栏中看到该内容
        comment.setAuthor("hxx");

        // 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.createRow(0);

        // 表格的标题行
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 创建内容
        /*
         * for(int i=0;i<values.length;i++) { row = sheet.createRow(i+1); for(int
         * j=0;j<values[i].length();j++) { //将内容按顺序赋给对应的列对象
         * row.createCell(j).setCellValue(values[i][j]); } }
         */

        // 遍历集合数据,填充数据行
        Iterator<T> it = dataset.iterator();// 迭代器
        int index = 0;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            T t = (T) it.next();
            // 利用反射,根据javabean属性的先后顺序,动态调用get方法得到属性值
            // Field[] fields = t.getClass().getDeclaredFields();
            for (int i = 0; i < getMethods.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(style2);
                // Field field = fields[i];
                // String fieldName = field.getName();//属性名,例如:用户名称egpListUserMc
                // 拿到属性得get方法
                String getMethodName = getMethods[i];// 例如:getEgpListUserMc
                try {
                    Class tCls = t.getClass();// 拿到JavaBean对象
                    // 通过javaBean对象拿到该属性的get方法
                    Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
                    // 操作该对象属性的get方法,拿到属性值
                    Object value = getMethod.invoke(t, new Object[] {});
                    String gender = "";
                    if (value == null) {
                        row.createCell(i).setCellValue("");
                    } else {
                            row.createCell(i).setCellValue(value.toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return workbook;

    }
}
View Code

2、js方法

/*导出*/
        function exportUserList(){
            var flag = confirm("确定要导出数据?");
            if(flag==true){
                obj = document.getElementsByName("userIdCheckbox");
                ids = [];
                for(k in obj){
                    if(obj[k].checked)
                        ids.push(obj[k].value);
                }
                  if(ids =="" || ids == null){
                      alert("请选择要导出的数据!");
                      return ;
                  }
                 var url = "<%=webApp %>/pages/Ryxz/exportTxlUserList.do?ids="+ids;
                 window.parent.mainIframe.location.href=url;
            }
        }
View Code

3、Controller层

@RequestMapping("/pages/Ryxz/exportTxlUserList.do")
    @ResponseBody
    public Map<String, String> exportXls(String ids,HttpServletResponse response,HttpServletRequest request) throws Exception{
        Map<String, String> map = new HashMap<String, String>();
        String[] headers = {"姓名","性别","职务","办公电话","移动电话","电子邮箱"};//headers需与getMethods一一对应
        String[] getMethods= {"getEgpListUserMc","getEgpListUserXb","getEgpListUserZjMc","getEgpListUserDh","getEgpListUserYddh","getEgpListUserEmail"};
        try {
            List<EgpListUser> list = new ArrayList<EgpListUser>();
            //根据ids查找数据
            String[] idS = ids.split(",");
            for(int i=0;i<idS.length;i++) {
                list.add(egpUserBaseService.getEgpListUserByEgpListUserId(idS[i]));
            }
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
            String fileName = "单位通讯录导出表"+sdf.format(date)+".xls";
            String title = "单位通讯录导出表";

            HSSFWorkbook workbook = ExcelUtil.exprotExcel(title, headers,getMethods, list);
            
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));  
            OutputStream os = response.getOutputStream();
            workbook.write(os);
            os.flush();
            os.close();    
            map.put("flag", "SUCCESS");
        }catch (Exception e) {
            logger.error("数据导出失败!", e);
            map.put("flag", "ERROR");
        }
        return map;
    }
View Code

 

转载于:https://www.cnblogs.com/nachdenken/p/11280590.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值