java导出Excel表格
来源:互联网 发布:ubuntu top命令详解 编辑:程序博客网 时间:2024/06/06 00:46
最近自己着手写了一个前后端分离的后台管理系统(主要是写着玩,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 0
- 【Java】导出excel表格
- JAVA 导出 excel 表格
- Java导出excel表格
- 【Java】导出excel表格
- java 导出excel表格
- Java导出Excel表格
- Java导出excel表格
- java导出excel表格
- java导出Excel表格
- java导出Excel表格
- java导出excel表格
- Java导出excel表格
- Java导出excel表格
- java 导出excel表格
- Java导出Excel表格
- java 导出excel表格
- java导出excel表格:
- Java导出excel表格
- windows小知识
- python列表生成式
- 关于STM32L152 运行时程序卡在B.处的解决方法
- Python 安装和使用
- 【论文阅读笔记】A Multi-Task Learning Formulation for Predicting Disease Progression
- java导出Excel表格
- android ndk与sdk
- FreeMarker整合到Spring中
- python aiohttp简易使用教程
- 13、Android开发基础之数据存储-查看保存的数据
- Angular 路由
- C# 深拷贝源码
- Yii2 表单=>数据库时间戳存取转换
- JAVA反射中的getFields()方法和getDeclaredFields ()方法的区别