import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse; import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference; public class ExcelUtil {
public static String NO_DEFINE = "no_define";// 未定义的字段
public static String DEFAULT_DATE_PATTERN = "yyyy年MM月dd日 HH:mm:ss";// 默认日期格式
public static int DEFAULT_COLOUMN_WIDTH = 20; /**
* 导出Excel 97(.xls)格式
*
* @param title-标题行
* @param list-要输出的表单
* @param datePattern-日期格式,null则用默认日期格式
* @param colWidth-列宽,默认至少17个字节
* @param out-输出流
*/
public static void exportExcel(String title, List<FormExcelObject> list, String datePattern, int colWidth,
OutputStream out) {
if (datePattern == null)
datePattern = DEFAULT_DATE_PATTERN;
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
workbook.createInformationProperties();
workbook.getDocumentSummaryInformation().setCompany("********公司");
SummaryInformation si = workbook.getSummaryInformation();
si.setAuthor("LAY"); // 填加xls文件作者信息
si.setApplicationName("**系统导出程序"); // 填加xls文件创建程序信息
si.setComments("LAY is a programmer!"); // 填加xls文件作者信息
si.setTitle(title + "数据"); // 填加xls文件标题信息
si.setSubject(title + "数据导出Excel");// 填加文件主题信息
si.setCreateDateTime(new Date());
// 表头样式
HSSFCellStyle titleStyle = workbook.createCellStyle();
titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont titleFont = workbook.createFont();
titleFont.setFontHeightInPoints((short) 20);
titleFont.setBoldweight((short) 700);
titleStyle.setFont(titleFont);
// 列头样式
HSSFCellStyle headerStyle = workbook.createCellStyle();
headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont headerFont = workbook.createFont();
headerFont.setFontHeightInPoints((short) 12);
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
headerStyle.setFont(headerFont);
// 单元格样式
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
HSSFFont cellFont = workbook.createFont();
cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
cellStyle.setFont(cellFont); for (int j = 0; j < list.size(); j++) {
FormExcelObject formExcelObject = list.get(j);
Map<String, String> headMap = formExcelObject.getHeadMap();
JSONArray jsonArray = formExcelObject.getJsonArray();
String _title = formExcelObject.getTitle(); int k = 1;
// 生成一个(带标题)表格
HSSFSheet sheet = workbook.createSheet(_title + "-" + k);
// 设置列宽
int minBytes = colWidth < DEFAULT_COLOUMN_WIDTH ? DEFAULT_COLOUMN_WIDTH : colWidth;// 至少字节数
int[] arrColWidth = new int[headMap.size()];
// 产生表格标题行,以及设置列宽
String[] properties = new String[headMap.size()];
String[] headers = new String[headMap.size()];
int ii = 0;
for (Iterator<String> iter = headMap.keySet().iterator(); iter.hasNext();) {
String fieldName = iter.next(); properties[ii] = fieldName;
headers[ii] = fieldName; int bytes = fieldName.getBytes().length;
arrColWidth[ii] = bytes < minBytes ? minBytes : bytes;
sheet.setColumnWidth(ii, arrColWidth[ii] * 256);
ii++;
}
// 遍历集合数据,产生数据行
int rowIndex = 0;
for (Object obj : jsonArray) {
if (rowIndex == 65535 || rowIndex == 0) {
if (rowIndex != 0) {
sheet = workbook.createSheet(_title + "-" + (++k));
for (int i = 0; i < headers.length; i++) {
sheet.setColumnWidth(i, arrColWidth[i] * 256);
}
} HSSFRow titleRow = sheet.createRow(0);// 表头 rowIndex=0
titleRow.createCell(0).setCellValue(_title);
titleRow.getCell(0).setCellStyle(titleStyle);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1)); HSSFRow headerRow = sheet.createRow(1); // 列头 rowIndex =1
for (int i = 0; i < headers.length; i++) {
headerRow.createCell(i).setCellValue(headMap.get(headers[i]));
headerRow.getCell(i).setCellStyle(headerStyle); }
rowIndex = 2;// 数据内容从 rowIndex=2开始
}
JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
HSSFRow dataRow = sheet.createRow(rowIndex);
for (int i = 0; i < properties.length; i++) {
HSSFCell newCell = dataRow.createCell(i); Object o = jo.get(properties[i]);
String cellValue = "";
if (o == null)
cellValue = "";
else if (o instanceof Date)
cellValue = new SimpleDateFormat(datePattern).format(o);
else
cellValue = o.toString(); newCell.setCellValue(cellValue);
newCell.setCellStyle(cellStyle);
}
rowIndex++;
} } try {
workbook.write(out);
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 通过向response中写入数据实现web下载
*
* @param title-文件名
* @param formExcelObjectList-表单数据
* @param response-要写入数据的响应
*/
public static void downloadExcelFile(String title, List<FormExcelObject> formExcelObjectList,
HttpServletResponse response) {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
ExcelUtil.exportExcel(title, formExcelObjectList, null, 0, os);
byte[] content = os.toByteArray();
InputStream is = new ByteArrayInputStream(content);
// 设置response参数,可以打开下载页面
response.reset(); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
response.setHeader("Content-Disposition",
"attachment;filename=" + new String((title + ".xls").getBytes(), "iso-8859-1"));
response.setContentLength(content.length);
ServletOutputStream outputStream = response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(outputStream);
byte[] buff = new byte[8192];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
} public static class FormExcelObject {
private String title;
private Map<String, String> headMap;
private JSONArray jsonArray; public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
} public Map<String, String> getHeadMap() {
return headMap;
} public void setHeadMap(Map<String, String> headMap) {
this.headMap = headMap;
} public JSONArray getJsonArray() {
return jsonArray;
} public void setJsonArray(JSONArray jsonArray) {
this.jsonArray = jsonArray;
} } public static void main(String[] args) throws IOException {
System.out.println("正在生成数据....");
int count = 100000;
JSONArray ja = new JSONArray();
for (int i = 0; i < 100000; i++) {
Student s = new Student();
s.setName("POI" + i);
s.setAge(i);
s.setBirthday(new Date());
s.setHeight(i);
s.setWeight(i);
s.setSex(i / 2 == 0 ? false : true);
ja.add(s);
}
String jsonString = "{\"name\":\"姓名\",\"age\":\"年龄\",\"birthday\":\"生日\",\"height\":\"身高\",\"weight\":\"体重\",\"sex\":\"性别\"}";
LinkedHashMap<String, String> headMap = JSON.parseObject(jsonString,
new TypeReference<LinkedHashMap<String, String>>() {
});
String title = "测试";
OutputStream outXlsx = new FileOutputStream("D://b.xls");
System.out.println("正在导出xls....");
Date d2 = new Date();
FormExcelObject feo = new FormExcelObject();
feo.setTitle("测试title");
feo.setHeadMap(headMap);
feo.setJsonArray(ja);
List<FormExcelObject> list = new ArrayList<FormExcelObject>();
list.add(feo);
ExcelUtil.exportExcel(title, list, null, 0, outXlsx);
System.out.println("共" + count + "条数据,执行耗时" + (new Date().getTime() - d2.getTime()) + "ms");
outXlsx.close();
} public static class Student {
private String name;
private int age;
private Date birthday;
private float height;
private double weight;
private boolean sex; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
} public float getHeight() {
return height;
} public void setHeight(float height) {
this.height = height;
} public double getWeight() {
return weight;
} public void setWeight(double weight) {
this.weight = weight;
} public boolean isSex() {
return sex;
} public void setSex(boolean sex) {
this.sex = sex;
} public void setAge(Integer age) {
this.age = age;
}
}
}

maven项目需要在pom文件中加入以下

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>3.13</version>
</dependency>

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.7</version>
</dependency>

非maven项目中加入jar

fastjson-1.2.7.jar

poi-3.13.jar

注:HttpServletResponse相关类为tomcat中带有的jar,此处不予列出

POI生成Excel工具类的更多相关文章

  1. 自己封装的poi操作Excel工具类

    自己封装的poi操作Excel工具类 在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完 ...

  2. java里poi操作Excel工具类【我改】

    参考原文: https://www.cnblogs.com/yizhang/p/7244917.html 我改: package test; import java.io.File; import j ...

  3. POI读取excel工具类 返回实体bean集合(xls,xlsx通用)

    本文举个简单的实例 读取上图的 excel文件到 List<User>集合 首先 导入POi 相关 jar包 在pom.xml 加入 <!-- poi --> <depe ...

  4. 使用回调方式写POI导入excel工具类

    场景是这样的:为了做一个excel导入的功能,为了尽可能的写一个通用的工具类,将与poi有关的东西都封装起来,以便以其他人员只用关心自己的业务,不用和poi打交道. 写到最后,现在还是会有poi的东西 ...

  5. 使用POI导出EXCEL工具类并解决导出数据量大的问题

    POI导出工具类 工作中常常会遇到一些图表需要导出的功能,在这里自己写了一个工具类方便以后使用(使用POI实现). 项目依赖 <dependency> <groupId>org ...

  6. POI读取excel工具类(xls,xlsx通用)

    package com.boot.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotF ...

  7. poi读取excel工具类

    package com.manage.utils; import ch.qos.logback.core.net.SyslogOutputStream; import com.google.gson. ...

  8. Java 利用poi生成excel表格

    所需jar包,如下所示 写一个excel工具类 ExcelUtils .java import java.lang.reflect.Field; import java.util.Iterator; ...

  9. java操作excel 工具类

    java操作excel 可参考https://blog.csdn.net/xunwei0303/article/details/53213130 直接上代码: 一.java生成excel文件: pac ...

随机推荐

  1. C#设计模式总结 C#设计模式(22)——访问者模式(Vistor Pattern) C#设计模式总结 .NET Core launch.json 简介 利用Bootstrap Paginator插件和knockout.js完成分页功能 图片在线裁剪和图片上传总结 循序渐进学.Net Core Web Api开发系列【2】:利用Swagger调试WebApi

    C#设计模式总结 一. 设计原则 使用设计模式的根本原因是适应变化,提高代码复用率,使软件更具有可维护性和可扩展性.并且,在进行设计的时候,也需要遵循以下几个原则:单一职责原则.开放封闭原则.里氏代替 ...

  2. JavaScript 日期格式化 简单有用

    JavaScript 日期格式化 简单有用 代码例如以下,引入jquery后直接后增加下面代码刷新可測试 Date.prototype.Format = function (fmt) { //auth ...

  3. 【学习笔记】C#中HashTable和快速排序的用法,从单词频率统计小程序写起

    先瞎扯点别的.进入这个神圣的地方总需要些鞭策,阿西巴,我是被鞭策进来摆摊的程序猿.软件工程老师说,写程序,发博客,就来博客园.这是个号召力很强的口号.最近看网络营销 搜索引擎优化的书多一些,只能说王老 ...

  4. LVDS、MIPI、EDP、VGA、DVI、HDMI、DP3.0(雷电接口)

    1.LVDS 2.mipi 3.EDP:Embedded DisplayPort 4.VGA VGA接口的特性: 1)理论上能够支持2048x1536分辨率画面传输. 2)VGA由于是模拟信号传输,所 ...

  5. Swift中的switch 和 do while

    switch后面的()能够省略 OC中的switch假设没有break就会穿透(依次运行),在Swift中不会穿透(可理解默认就有break) OC中入股要在case中定义变量,必要要加上{}确定作用 ...

  6. iOS移动开发周报-第17期

    lhq iOS移动开发周报-第17期 前言 欢迎国内的iOS同行或技术作者向我提交周报线索,线索可以是新闻.教程.开发工具或开源项目,将相关文章的简介和链接在微博上发布并 @唐巧_boy 即可. [摘 ...

  7. 宜人贷蜂巢API网关技术解密之Netty使用实践

    一.背景 宜人贷蜂巢团队,由Michael创立于2013年,通过使用互联网科技手段助力金融生态和谐健康发展.自成立起一直致力于多维度数据闭环平台建设.目前团队规模超过百人,涵盖征信.电商.金融.社交. ...

  8. 使用无缓冲IO函数读写文件

    前言 本文介绍使用无缓冲IO函数进行文件读写. 所谓的无缓冲是指该IO函数通过调用系统调用实现,其实系统调用内部的读写实现也是使用了缓冲技术的. 读写步骤 1. 打开文件 open 函数 2. 读写文 ...

  9. 2015最新iherb海淘攻略-图文入门教程-6月免邮

    注:仅仅有首次下单才享有新人优惠10$,大家下单之后千万不要取消后.否则之后则不享有新人优惠. 注:眼下Sino-海淘客国际物流已取消,仅有UCS合众速递. IHerb是美国最热门的海淘海购网站之中的 ...

  10. mysql-connector-java与mysql版本的对应

    记录下mysql-connector-java与mysql版本的对应关系,已方便以后参考,这是最新版本对应, 时间:2017年5月23日 官网文档地址: https://dev.mysql.com/d ...