java导出Excel表格

最近自己着手写了一个前后端分离的后台管理系统(主要是写着玩,java还是熟悉一点,所以前后端均是自己写),后端使用的Java SpringMVC。后来想着在用户管理中添加一个导出功能,所以就上网查了资料,实现了简单的导出功能,在这里记录下自己的过程。

1、在java项目中引入导出功能需要的jar包

  poi-3.9.jar

  poi-examples-3.9.jar

  poi-excelant-3.9.jar

  poi-ooxml-3.9.jar

  poi-ooxml-schemas-3.9.jar

  poi-scratchpad-3.9.jar

 

  项目中使用的是maven结构,所以在pom.xml文件中添加如下部分:

  

 

2、domain实体类-SysUser.java

 

3、controller层-SysUserController.java

复制代码
package com.lin.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.lin.domain.data.ResData;
import com.lin.domain.data.ResListData;
import com.lin.domain.error.Error;
import com.lin.domain.sysUser.SysUser;
import com.lin.service.RoleService;
import com.lin.service.SysUserService;
import com.lin.utils.Aes;
import com.lin.utils.DateTimeUtils;
import com.lin.utils.ExcelUtil;
import com.lin.utils.ResponseUtils;
import com.lin.utils.Upload;
import com.lin.utils.Utils;
import com.sun.jersey.api.client.Client;

import net.sf.json.JSONObject;

/**
 * 后台用户-controller
 * @author libo
 */
@Controller
@RequestMapping("/sysUser")
public class SysUserController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private RoleService rService;
    
    @Value(value="${headImgPath}")    //后台图片保存地址
    private String headImgPath;
    
    @Value(value="${uploadHost}")
    private String uploadHost;    //项目host路径    
    
    @Value(value="${sysUserDefImg}")
    private String sysUserDefImg;    //系统用户默认头像
/**
     * 导出系统用户数据
     * @param req
     * @param res
     * @param name
     * @param phone
     * @param email
     * @param roleId
     * @param createTimeStart
     * @param createTimeEnd
     * @param status
     * @param departmentId
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value="/exportSysUsers.do", method=RequestMethod.GET)
    public void exportSysUsers(HttpServletRequest req,HttpServletResponse res,
            String name, String phone, String email, Integer roleId, String createTimeStart, String createTimeEnd, 
            Integer status, Integer departmentId) throws IOException{
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("name", "".equals(name) || null == name ? null : name);
        params.put("phone", "".equals(phone) || null == phone ? null : phone);
        params.put("email", "".equals(email) || null == email ? null : email);
        params.put("roleId", "".equals(roleId) || null == roleId ? null : roleId);
        params.put("createTimeStart", "".equals(createTimeStart) || null == createTimeStart ? null : createTimeStart+" 00:00:00");
        params.put("createTimeEnd", "".equals(createTimeEnd) || null == createTimeEnd ? null : createTimeEnd+" 23:59:59");
        params.put("status", "".equals(status) || null == status ? null : status);
        params.put("departmentId", "".equals(departmentId) || null == departmentId ? null : departmentId);
        
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String formatTime = sdf.format(d);
        String fileName="系统用户表-"+formatTime;
        //填充projects数据
        List<SysUser> userList = sysUserService.getUserList(params);
        List<Map<String,Object>> list=createExcelRecord(userList);
        String columnNames[]={"姓名", "性别", "邮箱", "电话", "部门", "角色", "状态", "创建时间"};//列名
        String keys[] = {"name", "gender", "email", "phone", "department", "role", "status", "createTime"};//map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list,keys,columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数,可以打开www.cqben.com下载页面
        res.reset();
        res.setContentType("application/vnd.ms-excel;charset=utf-8");
        res.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = res.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
    }
    
    /**
     * 生成Excel数据
     * @param userList
     * @return
     */
    private List<Map<String, Object>> createExcelRecord(List<SysUser> userList) {
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sheetName", "sheet1");
        listmap.add(map);
        SysUser user = null;
        for (int j = 0; j < userList.size(); j++) {
            user = userList.get(j);
            Map<String, Object> mapValue = new HashMap<String, Object>();
            mapValue.put("name", user.getName());
            mapValue.put("gender", (user.getGender()==1) ? "男":((user.getGender()==0) ? "女" : "保密"));
            mapValue.put("email", user.getEmail());
            mapValue.put("phone", user.getPhone());
            mapValue.put("department", user.getDepartment().getName());
            mapValue.put("role", user.getRole().getName());
            mapValue.put("status", user.getStatus()==1 ? "启用" : "禁用");
            mapValue.put("createTime", user.getCreateTime().substring(0, 19));
            listmap.add(mapValue);
        }
        return listmap;
    }
    
    
}
复制代码

 

4、前端部分

复制代码
     /**
         * 点击导出按钮,导出用户数据
         */
        $scope.exportData = function () {
            //请求接口的参数
            var name = $scope.nameSearch || '',                 //姓名
                phone = $scope.phoneSearch || '',              //电话
                email = $scope.emailSearch || '',              //邮箱
                roleId = $scope.roleIdSearch || '',            //角色id
                departmentId = $scope.departmentIdSearch || '', //部门id
                createTimeStart = $('#createTimeRange').val() ? $('#createTimeRange').val().substring(0,10)+' 00:00:00' : '',  //创建时间(起始时间)
                createTimeEnd = $('#createTimeRange').val() ? $('#createTimeRange').val().substring(13,23)+' 23:59:59' : '',   //创建时间(截止时间)
                status = $scope.statusSearch || '';             //状态(1=正常,0=禁用)

            var url = apiServ.sysUser.exportSysUsers.url+'?name='+name+'&phone='+phone+'&email='+email+'&roleId='+roleId+'&departmentId='+departmentId+
                '&createTimeStart='+createTimeStart+'&createTimeEnd='+createTimeEnd+'&status='+status;
            window.open(url);
        }
复制代码

 

5、效果-导出的文件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值