1.pom文件:

     <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>

2.controller 根据需要组装数据:

private List<Map<String, Object>> createList(List<User> users){
if(null == users) {
return null;
}
String[] keys = {"name", "gender", "phoneNo", "email"};
String[] excelHeader = {"姓名","性别", "手机号", "邮箱"};
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> model = new HashMap<String, Object>();
model.put("fileName", "用户表" + new Date().getTime());
model.put("sheetName", "表一");
model.put("title", "用户表");
model.put("keys", keys);
model.put("excelHeader", excelHeader);
list.add(model); for(User user : users) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", user.getName());
map.put("gender", user.getGender());
map.put("phoneNo", user.getPhoneNo());
map.put("email", user.getEmail());
list.add(map);
}
return list;
}

3.ExcelUtil:

  

private static final Logger        LOG    = LoggerFactory.getLogger(ExcelUtil.class);

    /**创建一个excel文件*/
private static Workbook createWorkBoot(String title,
String[] excelHeader, List<Map<String, Object>> list, String[] keys) {
Workbook workbook = new HSSFWorkbook();
//设置sheet的名字
Sheet sheet = workbook.createSheet(list.get(0).get("sheetName").toString());
/*设置表格宽度*/
for(int i = 0; i < keys.length; i++){
sheet.setColumnWidth(i, 35*150);
} /*font样式设置字体大小,是否加粗*/
Font titleFont = createFont(workbook, (short)20, true);
Font headerFont = createFont(workbook, (short)12, true);
Font bodyFont = createFont(workbook, (short)12, false);
/*cell通用样式*/
CellStyle titleStyle = createStyle(workbook, titleFont);
CellStyle headerStyle = createStyle(workbook, headerFont);
CellStyle bodyStyle = createStyle(workbook, bodyFont); // excel中当前行索引
int index = 0;
/*合并标题的单元格设置标题信息及样式 */
sheet.addMergedRegion(new CellRangeAddress(index, index, index,
excelHeader.length - 1));
Row titleRow = sheet.createRow(index++);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue(title);
titleCell.setCellStyle(titleStyle); /*设置表格头信息及样式*/
Row headerRow = sheet.createRow(index++);
for(int i = 0; i < excelHeader.length; i++) {
Cell headerCell = headerRow.createCell(i);
headerCell.setCellValue(excelHeader[i]);
headerCell.setCellStyle(headerStyle);
} /*设置每行每 列的值及样式
*Row为行,cell为方格
*创建i*j个方格并设置对应的属性值*/
for(int i = 1; i < list.size(); i++) {
Row bodyRow = sheet.createRow(index++);
for (int j = 0; j < keys.length; j++) {
Cell bodyCell = bodyRow.createCell(j);
bodyCell.setCellValue(list.get(i).get(keys[j]) == null ?
" " : list.get(i).get(keys[j]).toString());
bodyCell.setCellStyle(bodyStyle);
}
}
return workbook;
} /**设置字体大小,颜色,样式,是否加粗*/
private static Font createFont(Workbook workbook,
short fontHeightInPoints, boolean isBlod) {
Font font = workbook.createFont();
//字体大小
font.setFontHeightInPoints(fontHeightInPoints);
//字体颜色
font.setColor(IndexedColors.BLACK.getIndex());
//字体样式
font.setFontName("宋体");
//是否加粗
font.setBold(isBlod);
return font;
} /**设置字体居中显示,背景色,边框*/
private static CellStyle createStyle(Workbook workbook, Font font) {
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(font);
//居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);
//背景颜色
cellStyle.setFillForegroundColor(IndexedColors.WHITE.index);
cellStyle.setFillBackgroundColor(IndexedColors.WHITE.index);
cellStyle.setFillPattern(FillPatternType.FINE_DOTS);
//边框
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
return cellStyle;
} public static boolean exportExcel(HttpServletResponse response,List<Map<String, Object>> list) throws IOException {
String fileName = list.get(0).get("fileName").toString();
String[] excelHeader = (String [])list.get(0).get("excelHeader");
String[] keys = (String [])list.get(0).get("keys");
String title = list.get(0).get("title").toString(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
createWorkBoot(title, excelHeader, list, keys).write(baos);
} catch (IOException e) {
LOG.error("将workbook中信息写入输出流时失败");
return false;
}
byte[] content = baos.toByteArray();
InputStream is = new ByteArrayInputStream(content); response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
response.setHeader("Content-Disposition", "attachment;filename="
+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
ServletOutputStream sos = response.getOutputStream();
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(sos);
byte[] buff = new byte[2048];
int byteRead = 0;
while (-1 != (byteRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, byteRead);
}
} catch (IOException e) {
LOG.error("创建excel文件时失败");
return false;
} finally {
if (bos != null)
bos.close();
if (bis != null)
bis.close();
if(is != null)
is.close();
if(baos != null)
baos.close();
}
return true;
}

导出效果

  

springmvc poi实现报表导出的更多相关文章

  1. Ireport 报表导出 Poi + ireport 导出pdf, word ,excel ,htm

    Ireport 报表导出 Poi + ireport 导出pdf, doc ,excel ,html 格式 下面是报表导出工具类reportExportUtils 需要导出以上格式的报表 只需要调用本 ...

  2. Java使用POI实现数据导出excel报表

    Java使用POI实现数据导出excel报表 在上篇文章中,我们简单介绍了java读取word,excel和pdf文档内容 ,但在实际开发中,我们用到最多的是把数据库中数据导出excel报表形式.不仅 ...

  3. Spring Boot 入门(十二):报表导出,对比poi、jxl和esayExcel的效率

    本片博客是紧接着Spring Boot 入门(十一):集成 WebSocket, 实时显示系统日志写的 关于poi.jxl和esayExcel的介绍自行百度. jxl最多支持03版excel,所以单个 ...

  4. poi报表导出4.1.0版本工具类 导出并下载

    这一段时间,由于项目上线基于稳定,所以我这边在基于我们一期迭代的分支上优化一部分我们之前没有做的功能,报表导出.本身之前用的是3.5的版本,但是由于同事要写导入,写的代码只有4.1.0的版本支持,所以 ...

  5. JAVA将Excel中的报表导出为图片格式(一)问题背景

    如题所示,先抛出一个问题,如何使用JAVA将Excel中的报表导出为图片格式? 首先说一下这个问题的背景,也就是为什么博主会碰到这个问题 随着微信,易信之流大行其道,企业内部的办公交流.绩效考评甚至考 ...

  6. Java中使用poi导入、导出Excel

    一.介绍 当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统.银行系统).或者是:我们已经习惯用Excel打印.这样在我们实际 ...

  7. kettle工具实现报表导出的初步搭建

    1.下载kettle 国外网站:http://kettle.pentaho.org/需要FQ,下载慢 2.下载完成启动(windows)-->spoon.bat 3.进入界面,两个主要的tab页 ...

  8. JasperReport报表导出踩坑实录

    写在最前面 翻了翻博客,因为太忙,已经好久没认真总结过了. 正好趁着今天老婆出门团建的机会,记录下最近这段时间遇到的大坑-JasperReport. 六月份的时候写过一篇利用poi文件导入导出的小De ...

  9. 报表导出之easypoi的应用

    报表导出有很多种方法,像之前我有写过的jxl,poi,jasperreport又或者各种商业软件,这次来简单介绍下用了许久的开源轮子easypoi. easypoi的底层原理就不介绍了.因为官方文档的 ...

随机推荐

  1. [转]python os模块 常用命令

    python编程时,经常和文件.目录打交道,这是就离不了os模块.os模块包含普遍的操作系统功能,与具体的平台无关.以下列举常用的命令 1. os.name()——判断现在正在实用的平台,Window ...

  2. mysql 之修改初始密码

    转载自:https://www.cnblogs.com/ivictor/p/5142809.html 为了加强安全性,MySQL5.7为root用户随机生成了一个密码,在error log中,关于er ...

  3. 简谈const限定符

    const修饰的数据类型是常量类型,常量类型的对象和变量在定义初始化后是不能被更新的.其实只用记住这一个概念,就可以明白const操作对象的方法. 1)定义const常量 最简单的: const in ...

  4. FineReport——JS二次开发(下拉框)

    下拉框显示多列时,输入的内容检索的内容为显示值整行数据,而不是实际值. 下拉框选择之后,控件显示的是显示值而非实际值. 对于下拉框显示队列,可以有多种方法,但是经过测试大多数方法不适用,检索效率太低, ...

  5. django 上传图片、使用PIL制作缩略图并保存到sea的storage

    上传图片解析: SAE的设置指引如下: 处理用户上传文件 在setttings.py中添加以下配置. # 修改上传时文件在内存中可以存放的最大size为10m FILE_UPLOAD_MAX_MEMO ...

  6. hdu 1065(贪心)

    Wooden Sticks Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 20938   Accepted: 8872 De ...

  7. poj 2104(线段树)

    K-th Number Time Limit: 20000MS   Memory Limit: 65536K Total Submissions: 45653   Accepted: 15177 Ca ...

  8. centos安装更新Python2.7以及pip的安装

    一.首先对相关的软件进行更新 python -V yum -y update yum groupinstall -y development yum install -y zlib zlib-dev ...

  9. lr中exit(-1)和return 0的区别

    LR脚本实践:关于lr中exit(-1)和return 0的区别 exit(-1):从当前action里面exit(-1)所在行,当前迭代里面直接退出来,终止运行: return 0:忽略当前acti ...

  10. 部署centos6

    挂载镜像和导入镜像 mount /dev/cdrom /media ll /media/ cobbler import --path=/media --name=centos6.5--arch=x86 ...