工具类 (正式使用)
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行创建rows
HSSFRow 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) {
//取出的数据是Integer
value = String.valueOf(((Integer) (valueObject)).floatValue());
} else if (valueObject instanceof BigDecimal) {
//取出的数据是BigDecimal
value = 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").attr("action", url).attr("method", "post");
//表头参数
form.append($("").attr("type", "hidden").attr("name", "headNames").attr("value", headNames));
form.append($("").attr("type", "hidden").attr("name", "headKeys").attr("value", headKeys));
//页面查询条件
form.append($("").attr("type", "hidden").attr("name", "startTime").attr("value", $("#startTime").val()));
form.append($("").attr("type", "hidden").attr("name", "endTime").attr("value", $("#endTime").val()));
form.append($("").attr("type", "hidden").attr("name", "garageName").attr("value", $("#garageName").val()));
form.append($("").attr("type", "hidden").attr("name", "garageAddress").attr("value", $("#garageAddress").val()));
//提交
form.appendTo('body').submit().remove();
});
控制层(正式使用)
@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");
//查询参数转Map
Map reqMap = new HashMap();
//分页(共用查询函数)
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 pageInfo = svc.queryDynamic(reqMap);
List list = pageInfo.getContent();
//无数据时也要导出(不跳空白页)
if(list == null || list.size() == 0){
list = new ArrayList();
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 reqMap, HttpServletRequest request, HttpServletResponse response) {
try {
//查询数据及转换
List 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
调用2
@RequestMapping("/excelPoi0")
public void reportExcelPoi0(@RequestBody(required = false) Map reqMap, HttpServletRequest request, HttpServletResponse response) {
try {
//excel文件名
String fileName = "测试";
//excel标题
String title = "测试名称";
//excel列头信息
String[] rowsName = new String[] {"公司名称", "公司地址", "公司网址"};
//excel数据
List listObj = new ArrayList();
//查询数据及转换
List list = svc.findAll();
if(list != null && list.size() > 0){
Object[] obj = null;
for (int i=0; i
简单测试
@RequestMapping("/excelPoi2")
public void reportExcelPoi2(@RequestBody(required = false) Map 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 - 博客园



