这里主要前面是通过一个全局变量,在layui的done回调里拿到数据,然后将该数据导出到excel,这里要注意一点,下载excel不能用ajax方式,如果采用ajax下载默认会读取response返回的二进制数据,所以这里采用表单方式提交 数据。

依赖:SSM架构

  1. <!--poi导出数据到excel-->
  2. <dependency>
  3. <groupId>org.apache.poi</groupId>
  4. <artifactId>poi</artifactId>
  5. <version>3.11</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.apache.poi</groupId>
  9. <artifactId>poi-ooxml</artifactId>
  10. <version>3.11</version>
  11. </dependency>

  

前端部分

  1. <form action="/doExport.action" id="download_form" method="post" class="layui-inline" style="display: inline;">
  2. <input type="hidden" id="page_data" class="layui-inline" name="userList">
  3. <input type="button" class="layui-btn layui-btn-normal layui-inline" id="export_excel" value="导出数据"/>
  4. </form>

  

  1. $('#export_excel').on('click',function () {
  2. $('#page_data').val(JSON.stringify(userPage.data));
  3. $("#download_form").submit();
  4. //$.ajax();
  5. });

  

服务器端部分

1.Controller层接收数据

  1. @RequestMapping(value = "/doExport")
  2. @ResponseBody
  3. public void exportExcelData(HttpServletRequest request, HttpServletResponse response, @RequestParam String userList){
  4. List<MgUser> mgUsers = JSONArray.parseArray(userList,MgUser.class);
  5.  
  6. // ReturnResult returnResult = new ReturnResult();
  7. // 定义表的标题
  8. String title = "用户列表";
  9. //定义表的列名
  10. String[] rowsName = new String[] { "序号", "用户名", "密码", "性别", "昵称", "出生年月" };
  11. //定义表的内容
  12. ExcelUtil excelUtil = new ExcelUtil();
  13.  
  14. List<Object[]> dataList = new ArrayList<Object[]>();
  15.  
  16. for (int i=0;i<mgUsers.size();i++){
  17. Object[] objects = new Object[rowsName.length];
  18. objects[0] = mgUsers.get(i).getId();
  19. objects[1] = mgUsers.get(i).getUsername();
  20. objects[2] = mgUsers.get(i).getPassword();
  21. objects[3] = mgUsers.get(i).getGender();
  22. objects[4] = mgUsers.get(i).getNichen();
  23. objects[5] = mgUsers.get(i).getBirthday();
  24. dataList.add(objects);
  25. }
  26.  
  27. try {
  28. String fileName= new String("用户数据表.xlsx".getBytes("UTF-8"),"iso-8859-1"); //生成word文件的文件名
  29. excelUtil.exportExcel(title,rowsName,dataList,fileName,response);
  30. //returnInfo.setResult(true);
  31.  
  32. }catch (Exception e){
  33. e.printStackTrace();
  34. }
  35.  
  36. }

2.工具类

  1. import org.apache.poi.hssf.usermodel.*;
  2. import org.apache.poi.hssf.util.HSSFColor;
  3. import org.apache.poi.ss.util.CellRangeAddress;
  4.  
  5. import javax.servlet.http.HttpServletResponse;
  6. import java.io.IOException;
  7. import java.io.OutputStream;
  8. import java.util.List;
  9.  
  10. public class ExcelUtil {
  11.  
  12. /**
  13. * 导出excel
  14. * @param title 导出表的标题
  15. * @param rowsName 导出表的列名
  16. * @param dataList 需要导出的数据
  17. * @param fileName 生成excel文件的文件名
  18. * @param response
  19. */
  20.  
  21. public void exportExcel(String title, String[] rowsName, List<Object[]> dataList, String fileName, HttpServletResponse response) throws Exception{
  22. OutputStream output = response.getOutputStream();
  23. response.reset();
  24. response.setHeader("Content-disposition",
  25. "attachment; filename="+fileName);
  26. response.setContentType("application/msexcel");
  27. this.export(title,rowsName,dataList,fileName,output);
  28. this.close(output);
  29.  
  30. }
  31.  
  32. /*
  33. * 导出数据
  34. */
  35. private void export(String title,String[] rowName,List<Object[]> dataList,String fileName,OutputStream out) throws Exception {
  36. try {
  37. HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
  38. HSSFSheet sheet = workbook.createSheet(title); // 创建工作表
  39. HSSFRow rowm = sheet.createRow(0); // 产生表格标题行
  40. HSSFCell cellTiltle = rowm.createCell(0); //创建表格标题列
  41. // sheet样式定义; getColumnTopStyle(); getStyle()均为自定义方法 --在下面,可扩展
  42. HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);// 获取列头样式对象
  43. HSSFCellStyle style = this.getStyle(workbook); // 获取单元格样式对象
  44. //合并表格标题行,合并列数为列名的长度,第一个0为起始行号,第二个1为终止行号,第三个0为起始列好,第四个参数为终止列号
  45. sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));
  46. cellTiltle.setCellStyle(columnTopStyle); //设置标题行样式
  47. cellTiltle.setCellValue(title); //设置标题行值
  48. int columnNum = rowName.length; // 定义所需列数
  49. HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)
  50. // 将列头设置到sheet的单元格中
  51. for (int n = 0; n < columnNum; n++) {
  52. HSSFCell cellRowName = rowRowName.createCell(n); // 创建列头对应个数的单元格
  53. cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
  54. HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
  55. cellRowName.setCellValue(text); // 设置列头单元格的值
  56. cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式
  57. }
  58.  
  59. // 将查询出的数据设置到sheet对应的单元格中
  60. for (int i = 0; i < dataList.size(); i++) {
  61. Object[] obj = dataList.get(i); // 遍历每个对象
  62. HSSFRow row = sheet.createRow(i + 3); // 创建所需的行数
  63. for (int j = 0; j < obj.length; j++) {
  64. HSSFCell cell = null; // 设置单元格的数据类型
  65. if (j == 0) {
  66. cell = row.createCell(j, HSSFCell.CELL_TYPE_NUMERIC);
  67. cell.setCellValue(i + 1);
  68. } else {
  69. cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);
  70. if (!"".equals(obj[j]) && obj[j] != null) {
  71. cell.setCellValue(obj[j].toString()); // 设置单元格的值
  72. }
  73. }
  74. cell.setCellStyle(style); // 设置单元格样式
  75. }
  76. }
  77.  
  78. // 让列宽随着导出的列长自动适应
  79. for (int colNum = 0; colNum < columnNum; colNum++) {
  80. int columnWidth = sheet.getColumnWidth(colNum) / 256;
  81. for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
  82. HSSFRow currentRow;
  83. // 当前行未被使用过
  84. if (sheet.getRow(rowNum) == null) {
  85. currentRow = sheet.createRow(rowNum);
  86. } else {
  87. currentRow = sheet.getRow(rowNum);
  88. }
  89. if (currentRow.getCell(colNum) != null) {
  90. HSSFCell currentCell = currentRow.getCell(colNum);
  91. if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
  92. int length = currentCell.getStringCellValue()
  93. .getBytes().length;
  94. if (columnWidth < length) {
  95. columnWidth = length;
  96. }
  97. }
  98. }
  99. }
  100. if (colNum == 0) {
  101. sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
  102. } else {
  103. sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);
  104. }
  105. }
  106. workbook.write(out);
  107. } catch (Exception e) {
  108. e.printStackTrace();
  109. }
  110. }
  111.  
  112. /*
  113. * 列头单元格样式
  114. */
  115. private HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
  116.  
  117. // 设置字体
  118. HSSFFont font = workbook.createFont();
  119. // 设置字体大小
  120. font.setFontHeightInPoints((short) 11);
  121. // 字体加粗
  122. font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  123. // 设置字体名字
  124. font.setFontName("Courier New");
  125. // 设置样式;
  126. HSSFCellStyle style = workbook.createCellStyle();
  127. // 设置底边框;
  128. style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  129. // 设置底边框颜色;
  130. style.setBottomBorderColor(HSSFColor.BLACK.index);
  131. // 设置左边框;
  132. style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  133. // 设置左边框颜色;
  134. style.setLeftBorderColor(HSSFColor.BLACK.index);
  135. // 设置右边框;
  136. style.setBorderRight(HSSFCellStyle.BORDER_THIN);
  137. // 设置右边框颜色;
  138. style.setRightBorderColor(HSSFColor.BLACK.index);
  139. // 设置顶边框;
  140. style.setBorderTop(HSSFCellStyle.BORDER_THIN);
  141. // 设置顶边框颜色;
  142. style.setTopBorderColor(HSSFColor.BLACK.index);
  143. // 在样式用应用设置的字体;
  144. style.setFont(font);
  145. // 设置自动换行;
  146. style.setWrapText(false);
  147. // 设置水平对齐的样式为居中对齐;
  148. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  149. // 设置垂直对齐的样式为居中对齐;
  150. style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  151.  
  152. return style;
  153.  
  154. }
  155.  
  156. /*
  157. * 列数据信息单元格样式
  158. */
  159. private HSSFCellStyle getStyle(HSSFWorkbook workbook) {
  160. // 设置字体
  161. HSSFFont font = workbook.createFont();
  162. // 设置字体大小
  163. // font.setFontHeightInPoints((short)10);
  164. // 字体加粗
  165. // font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  166. // 设置字体名字
  167. font.setFontName("Courier New");
  168. // 设置样式;
  169. HSSFCellStyle style = workbook.createCellStyle();
  170. // 设置底边框;
  171. style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  172. // 设置底边框颜色;
  173. style.setBottomBorderColor(HSSFColor.BLACK.index);
  174. // 设置左边框;
  175. style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  176. // 设置左边框颜色;
  177. style.setLeftBorderColor(HSSFColor.BLACK.index);
  178. // 设置右边框;
  179. style.setBorderRight(HSSFCellStyle.BORDER_THIN);
  180. // 设置右边框颜色;
  181. style.setRightBorderColor(HSSFColor.BLACK.index);
  182. // 设置顶边框;
  183. style.setBorderTop(HSSFCellStyle.BORDER_THIN);
  184. // 设置顶边框颜色;
  185. style.setTopBorderColor(HSSFColor.BLACK.index);
  186. // 在样式用应用设置的字体;
  187. style.setFont(font);
  188. // 设置自动换行;
  189. style.setWrapText(false);
  190. // 设置水平对齐的样式为居中对齐;
  191. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  192. // 设置垂直对齐的样式为居中对齐;
  193. style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  194. return style;
  195. }
  196.  
  197. /**
  198. * 关闭输出流
  199. * @param os
  200. */
  201. private void close(OutputStream os) {
  202. if (os != null) {
  203. try {
  204. os.close();
  205. } catch (IOException e) {
  206. e.printStackTrace();
  207. }
  208. }
  209. }
  210.  
  211. }

导出表格数据到excel并下载(HSSFWorkbook版)的更多相关文章

  1. .NET使用Office Open XML导出大量数据到 Excel

    我相信很多人在做项目的都碰到过Excel数据导出的需求,我从最开始使用最原始的HTML拼接(将需要导出的数据拼接成TABLE标签)到后来happy的使用开源的NPOI, EPPlus等开源组件导出EX ...

  2. PHP导出MySQL数据到Excel文件

    PHP导出MySQL数据到Excel文件 转载 常会碰到需要从数据库中导出数据到Excel文件,用一些开源的类库,比如PHPExcel,确实比较容易实现,但对大量数据的支持很不好,很容易到达PHP内存 ...

  3. 导出网页表格数据为Excel文件的前端解决方案

    在工作中,我们有时会遇到这样的需求,比如:要把页面的表格数据导出为Excel文件.在此记录下自己用的解决方法.代码如下: function tableToExcel(data){ //要导出的数据,t ...

  4. vue 导出JSON数据为Excel

    1. 安装三个依赖 npm install file-saver --save npm install xlsx --save npm install script-loader --save-dev ...

  5. 导出数据库数据制成Excel和txt

    引用ICSharpCode.SharpZipLib.dll 1.编写压缩和解压代码 using System; using System.Collections.Generic; using Syst ...

  6. java 对excel操作 读取、写入、修改数据;导出数据库数据到excel

    ============前提加入jar包jxl.jar========================= // 从数据库导出数据到excel public List<Xskh> outPu ...

  7. C#通过OLEDB导出大数据到Excel

    C#导出数据到Excel,基本有两种方法,一种方法是通过Microsoft.Office.Interop.Excel.Application,一行一列的写入Excel中:另一种方法是通过OLEDB,利 ...

  8. 原生javaScript导出表格数据

    <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8&quo ...

  9. PHP导出MySQL数据到Excel

    经常会碰到需要从数据库中导出数据到Excel文件,用一些开源的类库,比如PHPExcel,确实比较容易实现,但对大量数据的支持很不好,很容易到达PHP内存使用上限.这里的方法是利用fputcsv写CS ...

随机推荐

  1. Visio流程图表

    基本流程图: 流程图类别 基本流程图的四种类型 打开基本流程图 注意页面内引用跟跨页引用 就是两个按钮的作用 就是一个按钮的作用 点击跳转 按钮设置好之后可以输入数字 方便区分跳转 下面是跨职能流程图 ...

  2. Mysql的SQL优化指北

    概述 在一次和技术大佬的聊天中被问到,平时我是怎么做Mysql的优化的?在这个问题上我只回答出了几点,感觉回答的不够完美,所以我打算整理一次SQL的优化问题. 要知道怎么优化首先要知道一条SQL是怎么 ...

  3. MSXM简单的使用

    // xml.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <string> #include <at ...

  4. 洛谷$1220$ 关路灯 记搜/$DP$

    \(Sol\) 约定\(pos\)为老张所处的位置的路灯号,\(i<pos,j>pos\). 显然,如果\(i\)和\(j\)都关了,那么它们之间的所有灯一定也都关了. 设\(f[i][j ...

  5. h5项目中关于ios手机软键盘导致页面变形的完美解决方案

    1.项目背景:vue项目,手机加短信验证码登录: 2.问题: 在ios中input吊起软键盘,输入完成后,收起软件盘,页面不会回弹,导致页面下方出现空白,也就是页面变形: 3.最开始的解决方案是,用i ...

  6. 基于 HTML5 WebGL 与 WebVR 3D 虚实现实的可视化培训系统

    前言 2019 年 VR, AR, XR, 5G, 工业互联网等名词频繁出现在我们的视野中,信息的分享与虚实的结合已经成为大势所趋,5G 是新一代信息通信技术升级的重要方向,工业互联网是制造业转型升级 ...

  7. Python for Data Analysis 学习心得(二) - pandas介绍

    一.pandas介绍 本篇程序上篇内容,在numpy下面继续介绍pandas,本书的作者是pandas的作者之一.pandas是非常好用的数据预处理工具,pandas下面有两个数据结构,分别为Seri ...

  8. java数据结构之常用排序算法

    冒泡排序 private void maopao(int arr[]) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j &l ...

  9. Go中的Package和Module分析

    Package 所谓package(包)其实就是代码的一种组织管理方式,代码多了就需要放入文件,文件多了就需要归类放入文件夹,就好比我们在给电脑装软件时会进行归类安装,其实也是有意无意对电脑软件安装的 ...

  10. 轻量级开源小程序SDK发车啦

    Magicodes.WxMiniProgram.Sdk 轻量级微信小程序SDK,支持.NET Framework以及.NET Core.目前已提供Abp模块的封装,支持开箱即用. Nuget 新的包 ...