基于poi封装的导出Excel文件框架(Java实现)

最近把数据导出为Excel文件并保存到本地,由于有很多功能都会用到导出功能,所以就简单封装了一个导出框架,分享给大家。

 

导出框架思路:

1.一个Map对应一条数据记录

2.多条数据存放在List对象中

3.为了简化导出框架,该框架是基于HttpServlet+Web项目实现,如果在SpringBoot或者SpringMVC框架中使用,就把Servlet中代码写到Service业务逻辑层即可。

 

基于MyEclipse完整项目的源码下载,点击下载   

 

下面直接贴代码:

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        List<PageData> list=new ArrayList<PageData>();
        PageData pd1=new PageData();
        pd1.put("name", "张三");
        pd1.put("mobile", "18311234567");
        list.add(pd1);
        list.add(pd1);
        HSSFWorkbook wb=null;
        try {
            wb = this.generateWorkbook(list);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        response.setHeader("Content-Disposition", "attachment;filename="
                + new String("演示.xls".getBytes("gb2312"), "iso8859-1"));// 指定下载的文件名
        response.setContentType("application/vnd.ms-excel");
        OutputStream out = new BufferedOutputStream(response.getOutputStream());
        wb.write(out);
        out.flush();
        out.close();
    }

    private HSSFWorkbook generateWorkbook(List<PageData> orderList)
            throws Exception {
        // 声明一个工作薄
        HSSFWorkbook wb = new HSSFWorkbook();
        // 声明一个单子并命名
        HSSFSheet sheet = wb.createSheet("工单信息");

        // 冻结标题(width * height)
        // sheet.createFreezePane(15, 1);
        // 给单子名称一个长度
        sheet.setDefaultColumnWidth((short) 15);
        // 生成一个样式
        HSSFCellStyle style = wb.createCellStyle();
        // 设置表头颜色
        HSSFFont font = wb.createFont();
        font.setColor(HSSFColor.BLUE.index);
        style.setFont(font);
        // 水平布局 居中
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 上下居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 不锁定
        style.setLocked(false);
        // 设置边框
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
        // 创建第一行(也可以称为表头)
        HSSFRow row = sheet.createRow(0);
        // 样式字体居中
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        this.createExcelTitle(row, style);
        int k = 0;
        int orderSize = orderList == null ? 0 : orderList.size();
        for (int i = 0; i < orderSize; i++) {
            k++;
            row = sheet.createRow(k);
            this.addExcelContent(row, orderList.get(i));
            // row.createCell((short) 1).setCellValue(new
            // HSSFRichTextString(StringUtil.isNullObject(orderList.get(i).get("orderId")+"")));
        }
        return wb;
    }

    /**
     * 
     * 功能描述:创建工单title.
     * 
     */
    private void createExcelTitle(HSSFRow row, HSSFCellStyle style) {
        String[] titles = { "姓名", "手机号" };
        for (int i = 0; i < titles.length; i++) {
            String title = titles[i];
            // 给表头第一行一次创建单元格
            HSSFCell cell = row.createCell((short) i);
            cell.setCellValue(title);
            cell.setCellStyle(style);
        }
    }

    /**
     * 
     * 功能描述:增加一条数据记录.
     * 
     */
    private void addExcelContent(HSSFRow row, PageData pageData) {
        String[] fields = { "name", "mobile" };
        for (int i = 0; i < fields.length; i++) {
            String field = fields[i];
            row.createCell((short) i).setCellValue(
                    new HSSFRichTextString(pageData
                            .get(field) + ""));
        }
    }

PageData.java

public class PageData extends HashMap implements Map {

    private static final long serialVersionUID = 1L;

    Map map = null;
    HttpServletRequest request;

    public PageData(HttpServletRequest request) {
        this.request = request;
        Map properties = request.getParameterMap();
        Map returnMap = new HashMap();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        map = returnMap;
    }

    public PageData() {
        map = new HashMap();
    }

    @Override
    public Object get(Object key) {
        Object obj = null;
        if (map.get(key) instanceof Object[]) {
            Object[] arr = (Object[]) map.get(key);
            obj = request == null ? arr
                    : (request.getParameter((String) key) == null ? arr
                            : arr[0]);
        }else if ((map.get(key) instanceof Integer)||(map.get(key) instanceof Long)) {
            obj=String.valueOf(map.get(key));
        }else {
            obj = map.get(key);
        }
        return obj;
    }

    public String getString(Object key) {
        String value=(String) get(key);
        if (null != value && !"".equals(value)) {
            value=value.trim();
        }
        return value;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Object put(Object key, Object value) {
        return map.put(key, value);
    }

    @Override
    public Object remove(Object key) {
        return map.remove(key);
    }

    public void clear() {
        map.clear();
    }

    public boolean containsKey(Object key) {
        // TODO Auto-generated method stub
        return map.containsKey(key);
    }

    public boolean containsValue(Object value) {
        // TODO Auto-generated method stub
        return map.containsValue(value);
    }

    public Set entrySet() {
        // TODO Auto-generated method stub
        return map.entrySet();
    }

    public boolean isEmpty() {
        // TODO Auto-generated method stub
        return map.isEmpty();
    }

    public Set keySet() {
        // TODO Auto-generated method stub
        return map.keySet();
    }

    @SuppressWarnings("unchecked")
    public void putAll(Map t) {
        // TODO Auto-generated method stub
        map.putAll(t);
    }

    public int size() {
        // TODO Auto-generated method stub
        return map.size();
    }

    public Collection values() {
        // TODO Auto-generated method stub
        return map.values();
    }

}
 

基于MyEclipse完整项目的源码下载,点击下载   

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋9

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值