工具类 (正式使用)

package com.qyj.utils;import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;public class ExportExcelUtil {//文件名private String fileName;//表头private String title;//各个列的表头private String[] headName;//各个列的元素key值private String[] headKey;//需要填充的数据信息private JSONArray data;//字体大小private int fontSize = 10;//构造函数,传入要导出的数据public ExportExcelUtil(String fileName, String title, String[] headName, String[] headKey, JSONArray data) {this.fileName = fileName;this.title = title;this.headName = headName;this.headKey = headKey;this.data = data;}//导出public void export(HttpServletResponse response) {//创建工作簿HSSFWorkbook wb = new HSSFWorkbook();//创建工作表HSSFSheet sheet = wb.createSheet();//设置默认行宽sheet.setDefaultColumnWidth(15);//当前行索引int index = 0;//标题if(!StringUtils.isEmpty(title)){HSSFCellStyle cellStyleTitle = wb.createCellStyle();cellStyleTitle.setAlignment(HorizontalAlignment.CENTER);//水平居中cellStyleTitle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中HSSFFont fontStyleTitle = wb.createFont();fontStyleTitle.setBold(true);//加粗fontStyleTitle.setFontHeightInPoints((short)12);//设置标题字体大小cellStyleTitle.setFont(fontStyleTitle);//在第0行创建rows  (表标题)HSSFRow rowTitle = sheet.createRow(index++);rowTitle.setHeightInPoints(20);//行高HSSFCell cellValue = rowTitle.createCell(0);cellValue.setCellValue(title);cellValue.setCellStyle(cellStyleTitle);sheet.addMergedRegion(new CellRangeAddress(0,0,0,(headName.length-1)));}//表头HSSFCellStyle cellStyleHead = wb.createCellStyle();//设置单元格样式cellStyleHead.setAlignment(HorizontalAlignment.CENTER);cellStyleHead.setVerticalAlignment(VerticalAlignment.CENTER);//设置字体HSSFFont fontStyleHead = wb.createFont();fontStyleHead.setBold(true);//加粗fontStyleHead.setFontHeightInPoints((short)fontSize);cellStyleHead.setFont(fontStyleHead);//在第1行创建rowsHSSFRow row = sheet.createRow(index++);//设置列头元素HSSFCell cellHead = null;for (int i = 0; i < headName.length; i++) {cellHead = row.createCell(i);cellHead.setCellValue(headName[i]);cellHead.setCellStyle(cellStyleHead);}//数据//设置单元格样式HSSFCellStyle cellStyleData = wb.createCellStyle();cellStyleData.setWrapText(true);//自动换行cellStyleData.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中for (int i = 0; i < data.size(); i++) {HSSFRow rowTemp = sheet.createRow(index++);JSONObject map = (JSONObject)data.get(i);HSSFCell cell = null;for (int j = 0; j < headKey.length; j++) {cell = rowTemp.createCell(j);cell.setCellStyle(cellStyleData);Object valueObject = map.get(headKey[j]);String value = null;if (valueObject == null) {valueObject = "";}if (valueObject instanceof String) {//取出的数据是字符串直接赋值value = (String) map.get(headKey[j]);} else if (valueObject instanceof Integer) {//取出的数据是Integervalue = String.valueOf(((Integer) (valueObject)).floatValue());} else if (valueObject instanceof BigDecimal) {//取出的数据是BigDecimalvalue = String.valueOf(((BigDecimal) (valueObject)).floatValue());} else {value = valueObject.toString();}cell.setCellValue(StringUtils.isEmpty(value) ? "" : value);}}//让列宽随着导出的列长自动适应int maxColumnWidth = 30 * 256;int columnNum = headName.length;for (int colNum = 0; colNum < columnNum; colNum++) {//自动列宽sheet.autoSizeColumn(colNum);//like12 add,20220122,设置最大宽度限制int columnWidth = sheet.getColumnWidth(colNum);if(columnWidth > maxColumnWidth){columnWidth = maxColumnWidth;}//手动调整列宽,解决中文不能自适应问题sheet.setColumnWidth(colNum, columnWidth * 12 / 10);}//导出OutputStream out = null;try {out = response.getOutputStream();response.setCharacterEncoding("utf-8");response.setContentType("application/x-msdownload");//下面一行的设置作用:浏览器会提示保存还是打开,如果是保存,会提供一个默认的文件名response.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("gb2312"), "ISO-8859-1") + ".xls");//写入wb.write(out);wb.close();} catch (IOException e) {e.printStackTrace();} finally {try {//like12 find,bug,20220121,不加out.flush会导致后台被执行2次(解决window.location文件下载会执行2次 window.location.href多次触发问题)out.flush();out.close();} catch (Exception e) {e.printStackTrace();}}}
}

JS(Ajax下载 Post传参)(结合bootstrap table)(正式使用)

//导出Excel(POI模式)
$("#btn_ExportExcelPoi").click(function(){//表头信息var headNames = null;var headKeys = null;//获取显示的列 返回值为数组对象var cols = $('#tb_Table').bootstrapTable('getVisibleColumns');//表头拼装if(cols.length > 0){for(var i=0; i<cols.length; i++){//剔除无效列(编号及操作)if(cols[i].field == 0|| cols[i].field == ""//实际不会被执行(等效于==0)|| cols[i].field == null|| cols[i].field == undefined){continue;}if(headNames == null){headNames = cols[i].title;headKeys = cols[i].field;}else{headNames += "," + cols[i].title;headKeys += "," + cols[i].field;}}}//ajax下载文件(post)var url = "/garageInfo/exportExcelPoi";var form = $("<form></form>").attr("action", url).attr("method", "post");//表头参数form.append($("<input></input>").attr("type", "hidden").attr("name", "headNames").attr("value", headNames));form.append($("<input></input>").attr("type", "hidden").attr("name", "headKeys").attr("value", headKeys));//页面查询条件form.append($("<input></input>").attr("type", "hidden").attr("name", "startTime").attr("value", $("#startTime").val()));form.append($("<input></input>").attr("type", "hidden").attr("name", "endTime").attr("value", $("#endTime").val()));form.append($("<input></input>").attr("type", "hidden").attr("name", "garageName").attr("value", $("#garageName").val()));form.append($("<input></input>").attr("type", "hidden").attr("name", "garageAddress").attr("value", $("#garageAddress").val()));//提交form.appendTo('body').submit().remove();
});

控制层(正式使用)

/*** 导出Excel(POI模式 Ajax下载 Post传参)* @param request* @param response*/
@RequestMapping("/exportExcelPoi")
public void exportExcelPoi(HttpServletRequest request, HttpServletResponse response) {int maxSize = 5000;//最大允许导出数据条数String fileName = "export";//String title = "标题";String title = null;//传null时无标题行//获取参数String headNames = request.getParameter("headNames");String headKeys = request.getParameter("headKeys");String startTime = request.getParameter("startTime");String endTime = request.getParameter("endTime");String garageName = request.getParameter("garageName");String garageAddress = request.getParameter("garageAddress");//查询参数转MapMap<String,Object> reqMap = new HashMap<String,Object>();//分页(共用查询函数)reqMap.put("page", 0);reqMap.put("size", maxSize);//查询参数reqMap.put("startTime", startTime);reqMap.put("endTime", endTime);reqMap.put("garageName", garageName);reqMap.put("garageAddress", garageAddress);//查询数据及转换Page<GarageInfo> pageInfo = svc.queryDynamic(reqMap);List<GarageInfo> list = pageInfo.getContent();//无数据时也要导出(不跳空白页)if(list == null || list.size() == 0){list = new ArrayList<GarageInfo>();list.add(new GarageInfo());}//表头String[] headName = headNames.split(",");//设置表格表头字段String[] headKey = headKeys.split(",");//查询对应的字段//数据JSONArray data = (JSONArray)JSONArray.toJSON(list);//实体List转Json//导出(调用poi的工具类)ExportExcelUtil ex = new ExportExcelUtil(fileName, title, headName, headKey, data);ex.export(response);
}

JS(get请求模式)

//导出Excel(POI模式)
$("#btn_ExportExcelPoi").click(function(){window.location = "/company/exportExcelPoi";
});

控制层

@RequestMapping("/exportExcelPoi")
public void exportExcelPoi(@RequestBody(required = false) Map<String,Object> reqMap, HttpServletRequest request, HttpServletResponse response) {try {//查询数据及转换List<Company> list = svc.findAll();if(list != null && list.size() > 0){String fileName = "export";//String title = "标题";String title = null;String [] headName = new String[]{"公司名称", "公司地址", "公司网址", "电话", "总产值"};//设置表格表头字段String [] headKey = new String[]{"comname", "comaddress", "comurl", "contactmobile", "totaloutput"};//查询对应的字段JSONArray data = (JSONArray)JSONArray.toJSON(list);//实体List转Json//导出(调用poi的工具类)ExportExcelUtil ex = new ExportExcelUtil(fileName, title, headName, headKey, data);ex.export(response);}} catch (Exception e) {e.printStackTrace();}
}

工具类2(未用-只能按顺序取值)

package com.qyj.utils;import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;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.HSSFRichTextString;
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.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;public class ExcelExportUtil0 {// 显示的导出表的标题private String title;// 导出表的列名private String[] rowName;// 数据private List<Object[]> dataList = new ArrayList<Object[]>();// 构造函数,传入要导出的数据public ExcelExportUtil0(String title, String[] rowName, List<Object[]> dataList) {this.title = title;this.rowName = rowName;this.dataList = dataList;}// 导出数据public void export(OutputStream out) throws Exception {try {HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet(title);// 产生表格标题行HSSFRow rowm = sheet.createRow(0);HSSFCell cellTitle = rowm.createCell(0);//sheet样式定义【】//HSSFCellStyle columnTopStyle = this.getColumnTopStyle(wb);//HSSFCellStyle style = this.getStyle(wb);sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));//cellTitle.setCellStyle(columnTopStyle);cellTitle.setCellValue(title);// 定义所需列数int columnNum = rowName.length;HSSFRow rowRowName = sheet.createRow(2);// 将列头设置到sheet的单元格中for (int n = 0; n < columnNum; n++) {HSSFCell cellRowName = rowRowName.createCell(n);cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);HSSFRichTextString text = new HSSFRichTextString(rowName[n]);cellRowName.setCellValue(text);//cellRowName.setCellStyle(columnTopStyle);}// 将查询到的数据设置到sheet对应的单元格中for (int i = 0; i < dataList.size(); i++) {Object[] obj = dataList.get(i);// 遍历每个对象HSSFRow row = sheet.createRow(i + 3);// 创建所需的行数for (int j = 0; j < obj.length; j++) {HSSFCell cell = null;if (j == 0) {cell = row.createCell(j, HSSFCell.CELL_TYPE_NUMERIC);cell.setCellValue(i + 1);} else {cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);if (!"".equals(obj[j]) && obj[j] != null) {cell.setCellValue(obj[j].toString());}}//cell.setCellStyle(style);}}// 让列宽随着导出的列长自动适应for (int colNum = 0; colNum < columnNum; colNum++) {int columnWidth = sheet.getColumnWidth(colNum) / 256;for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {HSSFRow currentRow;if (sheet.getRow(rowNum) == null) {currentRow = sheet.createRow(rowNum);} else {currentRow = sheet.getRow(rowNum);}if (currentRow.getCell(colNum) != null) {HSSFCell currentCell = currentRow.getCell(colNum);if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {int length = currentCell.getStringCellValue().getBytes().length;if (columnWidth < length) {columnWidth = length;}}}}if (colNum == 0) {sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);} else {sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);}}if (wb != null) {try {wb.write(out);wb.close();} catch (Exception e) {e.printStackTrace();}}} catch (Exception e) {}}/** 列头单元格样式*//*public HSSFCellStyle getColumnTopStyle(HSSFWorkbook wb) {// 设置字体HSSFFont font = wb.createFont();// 设置字体大小font.setFontHeightInPoints((short) 11);// 字体加粗font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 设置字体名字font.setFontName("Courier New");// 设置样式HSSFCellStyle style = wb.createCellStyle();// 设置低边框style.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 设置低边框颜色style.setBottomBorderColor(HSSFColor.BLACK.index);// 设置右边框style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 设置顶边框style.setTopBorderColor(HSSFColor.BLACK.index);// 设置顶边框颜色style.setTopBorderColor(HSSFColor.BLACK.index);// 在样式中应用设置的字体style.setFont(font);// 设置自动换行style.setWrapText(false);// 设置水平对齐的样式为居中对齐;style.setAlignment(HSSFCellStyle.ALIGN_CENTER);style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);return style;}*//*public HSSFCellStyle getStyle(HSSFWorkbook wb) {// 设置字体HSSFFont font = wb.createFont();// 设置字体大小font.setFontHeightInPoints((short) 10);// 字体加粗font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 设置字体名字font.setFontName("Courier New");// 设置样式;HSSFCellStyle style = wb.createCellStyle();// 设置底边框;style.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 设置底边框颜色;style.setBottomBorderColor(HSSFColor.BLACK.index);// 设置左边框;style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 设置左边框颜色;style.setLeftBorderColor(HSSFColor.BLACK.index);// 设置右边框;style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 设置右边框颜色;style.setRightBorderColor(HSSFColor.BLACK.index);// 设置顶边框;style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 设置顶边框颜色;style.setTopBorderColor(HSSFColor.BLACK.index);// 在样式用应用设置的字体;style.setFont(font);// 设置自动换行;style.setWrapText(false);// 设置水平对齐的样式为居中对齐;style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置垂直对齐的样式为居中对齐;style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);return style;}*/
}

调用2

@RequestMapping("/excelPoi0")
public void reportExcelPoi0(@RequestBody(required = false) Map<String,Object> reqMap, HttpServletRequest request, HttpServletResponse response) {try {//excel文件名String fileName = "测试";//excel标题String title = "测试名称";//excel列头信息String[] rowsName = new String[] {"公司名称", "公司地址", "公司网址"};//excel数据List<Object[]> listObj = new ArrayList<Object[]>();//查询数据及转换List<Company> list = svc.findAll();if(list != null && list.size() > 0){Object[] obj = null;for (int i=0; i<list.size(); i++) {Company com = list.get(i);obj = new Object[rowsName.length];obj[0] = com.getComname();obj[1] = com.getComaddress();obj[2] = com.getComurl();listObj.add(obj);}}OutputStream out = null;try {out = response.getOutputStream();//response.setContentType("application/ms-excel;charset=UTF-8");//response.setHeader("Content-Disposition", "attachment;filename="//        .concat(String.valueOf(URLEncoder.encode(fileName + ".xls", "UTF-8"))));response.setCharacterEncoding("utf-8");response.setContentType("application/x-msdownload");//下面一行的设置作用:浏览器会提示保存还是打开,如果是保存,会提供一个默认的文件名response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO-8859-1") + ".xls");//调用poi的工具类ExcelExportUtil0 ex = new ExcelExportUtil0(title, rowsName, listObj);try {ex.export(out);} catch (Exception e) {e.printStackTrace();}} catch (IOException e) {System.out.println("输出流错误");e.printStackTrace();} finally {//like12 find,bug,20220121,不加out.flush会导致后台被执行2次(解决window.location文件下载会执行2次 window.location.href多次触发问题)out.flush();out.close();}} catch (Exception e) {//打印异常e.printStackTrace();}
}

简单测试

@RequestMapping("/excelPoi2")
public void reportExcelPoi2(@RequestBody(required = false) Map<String,Object> reqMap, HttpServletRequest request, HttpServletResponse response) {try {Workbook wb = new HSSFWorkbook();Sheet sheet = wb.createSheet();//标题行Row row = sheet.createRow(0);Cell cell = row.createCell(0);cell.setCellValue("公司名称");cell = row.createCell(1);cell.setCellValue("公司地址");cell = row.createCell(2);cell.setCellValue("公司网址");//数据行for(int i=1; i<11; i++){row = sheet.createRow(i);cell = row.createCell(0);cell.setCellValue("有限公司" + i);cell = row.createCell(1);cell.setCellValue("北京路" + i);cell = row.createCell(2);cell.setCellValue("http://www" + i + ".qyj.com");}String fileName = "测试";OutputStream out = null;try {out = response.getOutputStream();//response.setContentType("application/ms-excel;charset=UTF-8");//response.setHeader("Content-Disposition", "attachment;filename="//        .concat(String.valueOf(URLEncoder.encode(fileName + ".xls", "UTF-8"))));response.setCharacterEncoding("utf-8");response.setContentType("application/x-msdownload");//下面一行的设置作用:浏览器会提示保存还是打开,如果是保存,会提供一个默认的文件名response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO-8859-1") + ".xls");wb.write(out);wb.close();} catch (IOException e) {System.out.println("输出流错误");e.printStackTrace();} finally {//like12 find,bug,20220121,不加out.flush会导致后台被执行2次(解决window.location文件下载会执行2次 window.location.href多次触发问题)out.flush();out.close();}} catch (Exception e) {//打印异常e.printStackTrace();}
}

参考:

JAVA实现文件导出Excel - 迷你熊爱你 - 博客园

java导出excel的两种方式_jiankang66的博客-CSDN博客_java导出excel

bootstrap table getVisibleColumns获取显示的列的方法 - itxst.com

ajax方式下载文件 - nuccch - 博客园

java导出Excel(POI模式 Ajax下载 Post传参) bootstrap table getVisibleColumns获取显示的列相关推荐

  1. JAVA导出excel 直接弹出下载框

    效果展示: 1.首先准备jar包 <dependency><groupId>org.apache.poi</groupId><artifactId>po ...

  2. java 浏览器 excel导出excel_使用Java导出Excel表格并由浏览器直接下载——基于POI框架...

    非异步方法 /** * 使用Java导出Excel表格并由浏览器直接下载--基于POI框架 * * @param response * @return * @throws IllegalAccessE ...

  3. Java POI 导出EXCEL经典实现 Java导出Excel弹出下载框

    原文转载:http://blog.csdn.net/evangel_z/article/details/7332535 目录(?)[+] 在web开发中,有一个经典的功能,就是数据的导入导出.特别是数 ...

  4. java导出excel设置行高列宽_使用POI生成Excel文件,可以自动调整excel列宽

    //autoSizeColumn()方法自动调整excel列宽 importjava.io.FileOutputStream; importorg.apache.poi.hssf.usermodel. ...

  5. JAVA导出Excel通用工具类——第一篇:详细介绍POI 导出excel的多种复杂情况,包括动态设置筛选、动态合并横向(纵向)单元格等多种复杂情况——保姆级别,真的不能再详细了,代码拿来即用)

    JAVA导出Excel通用工具--第一篇:详细介绍POI 导出excel的多种复杂情况,包括动态设置筛选.动态合并横向(纵向)单元格等多种复杂情况--保姆级别,真的不能再详细了,封装通用工具类,代码拿 ...

  6. java导出excel压缩包_java动态导出excel压缩成zip下载的方法

    本文实例为大家分享了java动态导出excel压缩成zip下载的具体代码,供大家参考,具体内容如下 package pack.java.io.demo; import java.io.Buffered ...

  7. POI:java导出excel,java设置单元格公式,求和

    POI:java设置单元格公式,求和 java导出excel,之前写过全量导出,但是有时候报表中需要汇总,或者其他公式的数据. 这里就需要对单元格的格式调整,设置公式 主要代码 //给单元格设置公式 ...

  8. java导出excel并实现下载功能

    java导出excel并实现下载功能 这里我们使用alibaba的依赖包 <dependency><groupId>com.alibaba</groupId>< ...

  9. java导出excel组件alibaba easyexcel和apache poi性能对比

    java导出excel组件alibaba easyexcel和apache poi性能对比 背景: 开发中出现web页面导出记录到excel导致服务oom奔溃,代码中使用apache poi组件导出, ...

最新文章

  1. Linux系统基础调优
  2. mongo 3t 处理时间
  3. 软件项目管理0703:净收确认
  4. 51nod 1277 KMP 前缀出现次数
  5. pgsql_sql查询效率优化
  6. CF1028F. Make Symmetrical
  7. 【OpenCV 例程200篇】88. 频率域拉普拉斯高通滤波
  8. python大数据招聘信息_2017招聘大数据丨Python需求增速达174%,AI人才缺口超百万!...
  9. 真强啊!建议每一个打算学Java的人都来看看!
  10. nginx 多个root_dockerfile定制自己的nginx
  11. bzoj 4034: [HAOI2015]树上操作(树链剖分+线段树区间更新)
  12. 易筋SpringBoot 2.1 | 第六篇:JdbcTemplate访问MySQL
  13. Brocade 光纤交换机配置命令
  14. 关于微信小程序img标签不能显示图片的问题
  15. 电子之TTL和CMOS门电路的区别
  16. 自定义 UINavigationController
  17. paired-end reads的拼接
  18. Hello 中国,Go官网回归中国
  19. 格鲁夫给经理人的第一课
  20. vue框架在ie浏览器下的问题以及解决方法

热门文章

  1. 我们小时候可没这么牛的露天电影
  2. Android仿淘宝京东商品规格参数颜色筛选
  3. html css图标怎么跟文字并排,科技常识:css图标与文字对齐的两种实现方法
  4. VUE—下载安装并使用mint ui(图文详情)
  5. 浙大图灵班今年首次招生:院士授课,本科生配学业导师
  6. Angular 4入门教程系列:14:PrimeNG的使用方式
  7. JavaScript replace() 方法转换时间数据中的“-”和“/”
  8. 内存类型UDIMM、RDIMM、LRDIMM
  9. android模拟器比较好,安卓模拟器哪个好用,好用的安卓模拟器有哪些
  10. 挂断电话的实现(即类似于电话号码黑名单)