1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>fastjson</artifactId>
  4. <version>1.2.38</version>
  5. </dependency>
  6.  
  7. <dependency>
  8. <groupId>org.apache.poi</groupId>
  9. <artifactId>poi-ooxml</artifactId>
  10. <version>3.16</version>
  11. </dependency>
  1. package com.demo.util;
  2.  
  3. import java.io.BufferedInputStream;
  4. import java.io.BufferedOutputStream;
  5. import java.io.ByteArrayInputStream;
  6. import java.io.ByteArrayOutputStream;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.OutputStream;
  11. import java.math.BigDecimal;
  12. import java.text.SimpleDateFormat;
  13. import java.util.Date;
  14. import java.util.Iterator;
  15. import java.util.LinkedHashMap;
  16. import java.util.Map;
  17.  
  18. import javax.servlet.ServletOutputStream;
  19. import javax.servlet.http.HttpServletResponse;
  20.  
  21. import org.apache.poi.hpsf.SummaryInformation;
  22. import org.apache.poi.hssf.usermodel.HSSFCell;
  23. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  24. import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
  25. import org.apache.poi.hssf.usermodel.HSSFComment;
  26. import org.apache.poi.hssf.usermodel.HSSFFont;
  27. import org.apache.poi.hssf.usermodel.HSSFPatriarch;
  28. import org.apache.poi.hssf.usermodel.HSSFRichTextString;
  29. import org.apache.poi.hssf.usermodel.HSSFRow;
  30. import org.apache.poi.hssf.usermodel.HSSFSheet;
  31. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  32. import org.apache.poi.ss.usermodel.BorderStyle;
  33. import org.apache.poi.ss.usermodel.CellStyle;
  34. import org.apache.poi.ss.usermodel.Font;
  35. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  36. import org.apache.poi.ss.usermodel.IndexedColors;
  37. import org.apache.poi.ss.util.CellRangeAddress;
  38. import org.apache.poi.xssf.streaming.SXSSFCell;
  39. import org.apache.poi.xssf.streaming.SXSSFRow;
  40. import org.apache.poi.xssf.streaming.SXSSFSheet;
  41. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  42.  
  43. import com.alibaba.fastjson.JSONArray;
  44. import com.alibaba.fastjson.JSONObject;
  45.  
  46. /**
  47. *
  48. * @ClassName: ExcelUtil
  49. * @Description: TODO(这里用一句话描述这个类的作用)
  50. * @Author Louis
  51. * @DateTime 2017年9月14日 下午7:49:54
  52. * @Version V1.0
  53. */
  54.  
  55. public class ExcelUtil{
  56.  
  57. public static String NO_DEFINE = "no_define";//未定义的字段
  58. public static String DEFAULT_DATE_PATTERN="yyyy年MM月dd日";//默认日期格式
  59. public static int DEFAULT_COLOUMN_WIDTH = 18;
  60. /**
  61. * 导出Excel 97(.xls)格式 ,少量数据
  62. * @param title 标题行
  63. * @param headMap 属性-列名
  64. * @param jsonArray 数据集
  65. * @param datePattern 日期格式,null则用默认日期格式
  66. * @param colWidth 列宽 默认 至少17个字节
  67. * @param out 输出流
  68. */
  69. public static void exportExcel(String title,Map<String, String> headMap,JSONArray jsonArray,String datePattern,int colWidth, OutputStream out) {
  70. if(datePattern==null) datePattern = DEFAULT_DATE_PATTERN;
  71. // 声明一个工作薄
  72. HSSFWorkbook workbook = new HSSFWorkbook();
  73. workbook.createInformationProperties();
  74. workbook.getDocumentSummaryInformation().setCompany("*****公司");
  75. SummaryInformation si = workbook.getSummaryInformation();
  76. si.setAuthor("JACK"); //填加xls文件作者信息
  77. si.setApplicationName("导出程序"); //填加xls文件创建程序信息
  78. si.setLastAuthor("最后保存者信息"); //填加xls文件最后保存者信息
  79. si.setComments("JACK is a programmer!"); //填加xls文件作者信息
  80. si.setTitle("POI导出Excel"); //填加xls文件标题信息
  81. si.setSubject("POI导出Excel");//填加文件主题信息
  82. si.setCreateDateTime(new Date());
  83. //表头样式
  84. HSSFCellStyle titleStyle = workbook.createCellStyle();
  85. titleStyle.setFillBackgroundColor((short) 200);
  86. HSSFFont titleFont = workbook.createFont();
  87. titleFont.setFontHeightInPoints((short) 20);
  88. titleStyle.setFont(titleFont);
  89. // 列头样式
  90. HSSFCellStyle headerStyle = workbook.createCellStyle();
  91. HSSFFont headerFont = workbook.createFont();
  92. headerFont.setFontHeightInPoints((short) 12);
  93. headerStyle.setFont(headerFont);
  94. // 单元格样式
  95. HSSFCellStyle cellStyle = workbook.createCellStyle();
  96. cellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
  97. cellStyle.setFillBackgroundColor(IndexedColors.RED.getIndex());
  98. HSSFFont cellFont = workbook.createFont();
  99. cellStyle.setFont(cellFont);
  100. // 生成一个(带标题)表格
  101. HSSFSheet sheet = workbook.createSheet();
  102. // 声明一个画图的顶级管理器
  103. HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
  104. // 定义注释的大小和位置,详见文档
  105. HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
  106. 0, 0, 0, (short) 4, 2, (short) 6, 5));
  107. // 设置注释内容
  108. comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));
  109. // 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.
  110. comment.setAuthor("JACK");
  111. //设置列宽
  112. int minBytes = colWidth<DEFAULT_COLOUMN_WIDTH?DEFAULT_COLOUMN_WIDTH:colWidth;//至少字节数
  113. int[] arrColWidth = new int[headMap.size()];
  114. // 产生表格标题行,以及设置列宽
  115. String[] properties = new String[headMap.size()];
  116. String[] headers = new String[headMap.size()];
  117. int ii = 0;
  118. for (Iterator<String> iter = headMap.keySet().iterator(); iter
  119. .hasNext();) {
  120. String fieldName = iter.next();
  121.  
  122. properties[ii] = fieldName;
  123. headers[ii] = fieldName;
  124.  
  125. int bytes = fieldName.getBytes().length;
  126. arrColWidth[ii] = bytes < minBytes ? minBytes : bytes;
  127. sheet.setColumnWidth(ii,arrColWidth[ii]*256);
  128. ii++;
  129. }
  130. // 遍历集合数据,产生数据行
  131. int rowIndex = 0;
  132. for (Object obj : jsonArray) {
  133. if(rowIndex == 65535 || rowIndex == 0){
  134. if ( rowIndex != 0 ) sheet = workbook.createSheet();//如果数据超过了,则在第二页显示
  135.  
  136. HSSFRow titleRow = sheet.createRow(0);//表头 rowIndex=0
  137. titleRow.createCell(0).setCellValue(title);
  138. titleRow.getCell(0).setCellStyle(titleStyle);
  139. sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));
  140.  
  141. HSSFRow headerRow = sheet.createRow(1); //列头 rowIndex =1
  142. for(int i=0;i<headers.length;i++)
  143. {
  144. headerRow.createCell(i).setCellValue(headers[i]);
  145. headerRow.getCell(i).setCellStyle(headerStyle);
  146.  
  147. }
  148. rowIndex = 2;//数据内容从 rowIndex=2开始
  149. }
  150. JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
  151. HSSFRow dataRow = sheet.createRow(rowIndex);
  152. for (int i = 0; i < properties.length; i++)
  153. {
  154. HSSFCell newCell = dataRow.createCell(i);
  155.  
  156. Object o = jo.get(properties[i]);
  157. String cellValue = "";
  158. if(o==null) cellValue = "";
  159. else if(o instanceof Date) cellValue = new SimpleDateFormat(datePattern).format(o);
  160. else cellValue = o.toString();
  161.  
  162. newCell.setCellValue(cellValue);
  163. newCell.setCellStyle(cellStyle);
  164. }
  165. rowIndex++;
  166. }
  167. // 自动调整宽度
  168. /*for (int i = 0; i < headers.length; i++) {
  169. sheet.autoSizeColumn(i);
  170. }*/
  171. try {
  172. workbook.write(out);
  173. workbook.close();
  174. } catch (IOException e) {
  175. e.printStackTrace();
  176. }
  177. }
  178. /**
  179. * 导出Excel 2007 OOXML (.xlsx)格式
  180. * @param title 标题行
  181. * @param headMap 属性-列头
  182. * @param jsonArray 数据集
  183. * @param datePattern 日期格式,传null值则默认 年月日
  184. * @param colWidth 列宽 默认 至少17个字节
  185. * @param out 输出流
  186. */
  187. public static void exportExcelX(String title,Map<String, String> headMap,JSONArray jsonArray,String datePattern,int colWidth, OutputStream out) {
  188. if(datePattern==null) datePattern = DEFAULT_DATE_PATTERN;
  189. // 声明一个工作薄
  190. SXSSFWorkbook workbook = new SXSSFWorkbook(1000);//缓存
  191. workbook.setCompressTempFiles(true);
  192. //表头样式
  193. CellStyle titleStyle = workbook.createCellStyle();
  194. titleStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex());
  195. Font titleFont = workbook.createFont();
  196. titleStyle.setFont(titleFont);
  197. // 列头样式
  198. CellStyle headerStyle = workbook.createCellStyle();
  199. headerStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex());
  200. headerStyle.setBorderBottom(BorderStyle.THIN);
  201. headerStyle.setBorderLeft(BorderStyle.THIN);
  202. headerStyle.setBorderTop(BorderStyle.THIN);
  203. headerStyle.setBorderRight(BorderStyle.THIN);
  204. headerStyle.setAlignment(HorizontalAlignment.CENTER);
  205. Font headerFont = workbook.createFont();
  206. headerFont.setFontName("Century Gothic");
  207. headerFont.setColor(IndexedColors.BLACK.getIndex());
  208. headerFont.setBold(true);
  209. headerStyle.setFont(headerFont);
  210. // 单元格样式
  211. CellStyle cellStyle = workbook.createCellStyle();
  212. // cellStyle.setFillPattern(HSSFCellStyle.FINE_DOTS );
  213. cellStyle.setFillBackgroundColor(IndexedColors.WHITE.index);
  214. cellStyle.setBorderBottom(BorderStyle.THIN);
  215. cellStyle.setBorderLeft(BorderStyle.THIN);
  216. cellStyle.setBorderTop(BorderStyle.THIN);
  217. cellStyle.setBorderRight(BorderStyle.THIN);
  218. cellStyle.setAlignment(HorizontalAlignment.CENTER);
  219. Font cellFont = workbook.createFont();
  220. cellFont.setFontName("Century Gothic");
  221. cellFont.setColor(IndexedColors.DARK_TEAL.getIndex());
  222. cellStyle.setFont(cellFont);
  223. // 生成一个(带标题)表格
  224. SXSSFSheet sheet = workbook.createSheet();
  225. //设置列宽
  226. int minBytes = colWidth<DEFAULT_COLOUMN_WIDTH?DEFAULT_COLOUMN_WIDTH:colWidth;//至少字节数
  227. int[] arrColWidth = new int[headMap.size()];
  228. // 产生表格标题行,以及设置列宽
  229. String[] properties = new String[headMap.size()];
  230. String[] headers = new String[headMap.size()];
  231. int ii = 0;
  232. for (Iterator<String> iter = headMap.keySet().iterator(); iter
  233. .hasNext();) {
  234. String fieldName = iter.next();
  235. properties[ii] = fieldName;
  236. headers[ii] = headMap.get(fieldName);
  237. int bytes = fieldName.getBytes().length;
  238. arrColWidth[ii] = bytes < minBytes ? minBytes : bytes;
  239. sheet.setColumnWidth(ii,arrColWidth[ii]*256);
  240. ii++;
  241. }
  242. // 遍历集合数据,产生数据行
  243. int rowIndex = 0;
  244. for (Object obj : jsonArray) {
  245. if(rowIndex == 65535 || rowIndex == 0){
  246. if ( rowIndex != 0 ) sheet = workbook.createSheet();//如果数据超过了,则在第二页显示
  247. SXSSFRow titleRow = sheet.createRow(0);//表头 rowIndex=0
  248. titleRow.createCell(0).setCellValue(title);
  249. titleRow.getCell(0).setCellStyle(titleStyle);
  250. sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));
  251. SXSSFRow headerRow = sheet.createRow(1); //列头 rowIndex =1
  252. for(int i=0;i<headers.length;i++)
  253. {
  254. headerRow.createCell(i).setCellValue(headers[i]);
  255. headerRow.getCell(i).setCellStyle(headerStyle);
  256. }
  257. rowIndex = 2;//数据内容从 rowIndex=2开始
  258. }
  259. JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
  260. SXSSFRow dataRow = sheet.createRow(rowIndex);
  261. for (int i = 0; i < properties.length; i++)
  262. {
  263. SXSSFCell newCell = dataRow.createCell(i);
  264. Object o = jo.get(properties[i]);
  265. String cellValue = "";
  266. if(o==null) cellValue = "";
  267. else if(o instanceof Date) cellValue = new SimpleDateFormat(datePattern).format(o);
  268. else if(o instanceof Float || o instanceof Double)
  269. cellValue= new BigDecimal(o.toString()).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
  270. else cellValue = o.toString();
  271. newCell.setCellValue(cellValue);
  272. newCell.setCellStyle(cellStyle);
  273. }
  274. rowIndex++;
  275. }
  276. try {
  277. workbook.write(out);
  278. workbook.close();
  279. workbook.dispose();
  280. } catch (IOException e) {
  281. e.printStackTrace();
  282. }
  283. }
  284. //Web 导出excel
  285. public static void downloadExcelFile(String title,Map<String,String> headMap,JSONArray ja,HttpServletResponse response){
  286. try {
  287. ByteArrayOutputStream os = new ByteArrayOutputStream();
  288. ExcelUtil.exportExcelX(title,headMap,ja,null,0,os);
  289. byte[] content = os.toByteArray();
  290. InputStream is = new ByteArrayInputStream(content);
  291. // 设置response参数,可以打开下载页面
  292. response.reset();
  293. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
  294. response.setHeader("Content-Disposition", "attachment;filename="+ new String((title + ".xlsx").getBytes(), "UTF-8"));
  295. response.setContentLength(content.length);
  296. ServletOutputStream outputStream = response.getOutputStream();
  297. BufferedInputStream bis = new BufferedInputStream(is);
  298. BufferedOutputStream bos = new BufferedOutputStream(outputStream);
  299. byte[] buff = new byte[8192];
  300. int bytesRead;
  301. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  302. bos.write(buff, 0, bytesRead);
  303.  
  304. }
  305. bis.close();
  306. bos.close();
  307. outputStream.flush();
  308. outputStream.close();
  309. }catch (Exception e) {
  310. e.printStackTrace();
  311. }
  312. }
  313.  
  314. public static void main(String[] args) throws IOException {
  315. int count = 100000;
  316. JSONArray ja = new JSONArray();
  317. for(int i=0;i<100000;i++){
  318. Student s = new Student();
  319. s.setName("POI"+i);
  320. s.setAge(i);
  321. s.setBirthday(new Date());
  322. s.setHeight(i);
  323. s.setWeight(i);
  324. s.setSex(i/2==0?false:true);
  325. ja.add(s);
  326. }
  327. Map<String,String> headMap = new LinkedHashMap<String,String>();
  328. headMap.put("name","姓名");
  329. headMap.put("age","年龄");
  330. headMap.put("birthday","生日");
  331. headMap.put("height","身高");
  332. headMap.put("weight","体重");
  333. headMap.put("sex","性别");
  334.  
  335. String title = "测试学生信息";
  336. OutputStream outXlsx = new FileOutputStream("E://Example.xlsx");
  337. System.out.println("正在导出xlsx....");
  338. Date d2 = new Date();
  339. ExcelUtil.exportExcelX(title,headMap,ja,null,18,outXlsx);
  340. System.out.println("共"+count+"条数据,执行"+(new Date().getTime()-d2.getTime())+"ms");
  341. outXlsx.close();
  342.  
  343. }
  344. }
  345. class Student {
  346.  
  347. private String name;
  348. private int age;
  349. private Date birthday;
  350. private float height;
  351. private double weight;
  352. private boolean sex;
  353.  
  354. public String getName() {
  355. return name;
  356. }
  357. public void setName(String name) {
  358. this.name = name;
  359. }
  360. public Integer getAge() {
  361. return age;
  362. }
  363. public Date getBirthday() {
  364. return birthday;
  365. }
  366. public void setBirthday(Date birthday) {
  367. this.birthday = birthday;
  368. }
  369. public float getHeight() {
  370. return height;
  371. }
  372. public void setHeight(float height) {
  373. this.height = height;
  374. }
  375. public double getWeight() {
  376. return weight;
  377. }
  378. public void setWeight(double weight) {
  379. this.weight = weight;
  380. }
  381. public boolean isSex() {
  382. return sex;
  383. }
  384. public void setSex(boolean sex) {
  385. this.sex = sex;
  386. }
  387. public void setAge(Integer age) {
  388. this.age = age;
  389. }
  390. }

POI Java 导出数据到Excel的更多相关文章

  1. Java导出数据为EXCEL的两种方式JXL和POI

    JXL和POI导出数据方式的比较 POI支持excel2003和2007,而jxl只支持excel2003. 下面为测试代码: public class TestCondition { /** * 生 ...

  2. 用poi来导出数据到excel文档

    package cn.com.dyg.work.common.utils; import org.apache.poi.hssf.usermodel.HSSFRichTextString; impor ...

  3. JAVA导出数据到excel中大数据量的解决方法

    最近在做项目功能时 ,发现有20万以上的数据.要求导出时直接导出成压缩包.原来的逻辑是使用poi导出到excel,他是操作对象集合然后将结果写到excel中. 使用poi等导出时,没有考虑数据量的问题 ...

  4. java导出数据到excel里:直接导出和导出数据库数据

    一.直接导出 package com.ij34.util; import java.io.FileNotFoundException; import java.io.FileOutputStream; ...

  5. Java导出数据生成Excel表格

    事先准备: 工具类: package com.wazn.learn.util.export; import java.sql.Connection; import java.sql.DriverMan ...

  6. Java导出数据行写入到Excel表格:基于Apache POI

    Java导出数据行写入到Excel表格:基于Apache POI import java.io.File; import java.io.FileOutputStream; import org.ap ...

  7. 从数据库导出数据到excel之POI操作

    项目说明: 1:数据库中有两张表,主键关联 2:根据条件查询数据 3:处理为需要的数据封装类型,然后传到导出excel的方法中 <--框架部署就不详谈了,用的spring框架--> 补充: ...

  8. java代码导出数据到Excel、js导出数据到Excel(三)

     jsp内容忽略,仅写个出发按钮:          <button style="width: 100px" onclick="expertExcel()&quo ...

  9. Java操作Jxl实现导出数据生成Excel表格数据文件

    实现:前台用的框架是Easyui+Bootstrap结合使用,需要引入相应的Js.Css文件.页面:Jsp.拦截请求:Servlet.逻辑处理:ClassBean.数据库:SQLserver. 注意: ...

随机推荐

  1. Ubuntu下安装软件

    在ubuntu当中,安装应用程序有三种方法,分别是:apt-get,dpkg安装deb和make install安装源码包三种. apt-get方法 使用apt-get install来安装应用程序算 ...

  2. 【jQuery】jquery.metadata.js验证失效

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...

  3. Project Server 2016 RestAPI调用测试

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xht ...

  4. C#自定义控件 ————进度条

    先看看样式 一个扇形的进度条 对外公开的方法和属性 事件 value_change;//值改变时触发的事件progress_finshed;//进度条跑完时触发的事件 属性 Max_value//获取 ...

  5. javaScript之深度理解原型链

    经过多次的翻阅书籍终于对原型链在实际代码中的应用有了新的认识,但是不知道是否有错误的地方,还请大神多多指教. 构造函数.原型和实例的关系:每个构造函数都有一个原型对象funName.prototype ...

  6. Java进阶之美文共享

    2.在Java中如何避免"!=null"式的判空语句?  3.Java问答:终极父类(3)  Java问答:终极父类(下) Java问答:终极父类(上) 内存不足:杀死进程还是牺牲 ...

  7. JS设置cookie、读取cookie、删除cookie(转)

    JS设置cookie.读取cookie.删除cookie 转载  2015-04-17   投稿:hebedich    我要评论 Js操作Cookie总结(设置,读取,删除),工作中经常会用到的哦! ...

  8. github 分支操作

    1.查看分支 1.查看本地分支 使用git branch命令,如下: $ git branch * master *标识的是你当前所在的分支. 2.查看远程分支 命令如下: git branch -r ...

  9. MySQL在linux下安装

    mysql在linux下的安装   安装环境:系统是 centos6.5 1.下载 下载地址:http://dev.mysql.com/downloads/mysql/5.6.html#downloa ...

  10. GCC源码编译

    1. gcc源码下载 ftp://gcc.gnu.org/pub/gcc/releases/ [yhwang@yhwang ~] wget ftp://gcc.gnu.org/pub/gcc/rele ...