SpringBoot导出excel表格
第一步 导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
第二步 编写导出excel表格的工具类
package com.xjpower.web.core.export;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.DateFormatConverter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.*;
import com.xjpower.web.core.export.ExcelExtGrid.GridColumn;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.view.document.AbstractExcelView;
@SuppressWarnings("unchecked")
public class ExcelExportView extends AbstractExcelView {
static final float PIX_TO_WIDTH = 100 * 50 / 132;
static final String DATE_COLUMN_XTYPE = "datecolumn";
static final String LINK_COLUMN_XTYPE = "linkcolumn";
static final String NUMBER_COLUMN_XTYPE = "numbercolumn ";
static final String BOOLEAN_COLUMN_XTYPE = "booleancolumn";
static final String COLUMN_XTYPE = "gridcolumn";
static final String getDefaultExportFileName() {
return "export.xls";
}
ExcelExtGrid grid = null;
List data = null;
public ExcelExportView(ExcelExtGrid grid, List data) {
this.grid = grid;
this.data = data;
}
protected void buildExcelDocument(Map model, HSSFWorkbook workbook, HttpServletRequest req, HttpServletResponse resp) throws Exception {
this.generateExcel(workbook, grid, data);
String fileName = StringUtils.isNotEmpty(grid.fileName) ? grid.fileName : getDefaultExportFileName();
fileName = fileName.endsWith(".xls") ? fileName : fileName + ".xls";
String filename = encodeFilename(fileName, req);
resp.setContentType("application/vnd.ms-excel");
resp.setHeader("Content-disposition", "attachment;filename=" + filename);
OutputStream ouputStream = resp.getOutputStream();
workbook.write(ouputStream);
ouputStream.flush();
ouputStream.close();
}
public static String encodeFilename(String filename, HttpServletRequest request) {
try {
return URLEncoder.encode(filename, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return filename;
}
Map<String, String> gridColumnXtypeFormat = null;
public Map<String, String> getGridColumnXtypeFormat() {
if (gridColumnXtypeFormat == null)
gridColumnXtypeFormat = new HashMap<String, String>();
String dateFormat = DateFormatConverter.convert(Locale.SIMPLIFIED_CHINESE, "yyyy-MM-dd HH:mm:ss");
gridColumnXtypeFormat.put(DATE_COLUMN_XTYPE, dateFormat);
return gridColumnXtypeFormat;
}
private int toColumnWidth(int pixWidth) {
Float colWdt = pixWidth * PIX_TO_WIDTH;
return colWdt.intValue();
}
@SuppressWarnings("unchecked")
protected HSSFWorkbook generateExcel(HSSFWorkbook workbook, ExcelExtGrid grid, List data) throws Exception {
workbook = workbook == null ? new HSSFWorkbook() : workbook;
HSSFSheet sheet = workbook.createSheet();
sheet.createFreezePane(1, 1);
HSSFCellStyle columnHeadStyle = getColumnHeaderStyle(workbook);
try {
HSSFRow row0 = sheet.createRow(0);
row0.setHeight((short) 500);
Map<String, HSSFCellStyle> columnStyleMap = new HashMap<String, HSSFCellStyle>();
for (int i = 0; i < grid.columns.size(); i++) {
GridColumn col = grid.columns.get(i);
if (col.width != null) {
sheet.setColumnWidth(i, toColumnWidth(col.width));
} else
sheet.setColumnWidth(i, toColumnWidth(100));
HSSFCell cell = row0.createCell(i);
cell.setCellStyle(columnHeadStyle);
cell.setCellValue(new HSSFRichTextString(col.header));
columnStyleMap.put(col.dataIndex, getDataCellStyle(workbook, col.xtype));
}
for (int i = 0; i < data.size(); i++) {
Object robj = data.get(i);
HSSFRow row = sheet.createRow(i + 1);
HSSFCell cell = null;
for (int c = 0; c < grid.columns.size(); c++) {
GridColumn col = grid.columns.get(c);
cell = row.createCell(c);
setDataCellValue(robj, cell, col, workbook);
cell.setCellStyle(columnStyleMap.get(col.dataIndex));
}
}
return workbook;
} catch (Exception e) {
throw new Exception("导出Excel文件[" + grid.fileName + "]出错", e);
}
}
private void setDataCellValue(Object rdata, HSSFCell cell, GridColumn col, HSSFWorkbook workbook) {
Object o = null;
if (rdata instanceof Map) {
o = ((Map) rdata).get(col.dataIndex);
} else {
o = getFieldValue(rdata, col.dataIndex);
}
if (o == null)
return;
if (DATE_COLUMN_XTYPE.equals(col.xtype)) {
if (o instanceof Date) {
cell.setCellValue((Date) o);
}
} else {
cell.setCellValue(o.toString());
}
}
public static Object getFieldValue(Object src, String valuePath) {
String[] valuePaths = valuePath.split("\\.");
Object o = src;
for (String field : valuePaths) {
Field f = ReflectionUtils.findField(src.getClass(), field);
ReflectionUtils.makeAccessible(f);
o = ReflectionUtils.getField(f, o);
}
return o;
}
private HSSFCellStyle getDataCellStyle(HSSFWorkbook workbook, String gridColumnXtype) {
HSSFFont font = workbook.createFont();
CreationHelper createHelper = workbook.getCreationHelper();
font.setFontName("宋体");
font.setFontHeightInPoints((short) 10);
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
style.setAlignment(CellStyle.ALIGN_LEFT);
style.setVerticalAlignment(CellStyle.VERTICAL_TOP);
style.setWrapText(true);
style.setLeftBorderColor(HSSFColor.BLACK.index);
style.setBorderLeft((short) 1);
style.setRightBorderColor(HSSFColor.BLACK.index);
style.setBorderRight((short) 1);
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setFillForegroundColor(HSSFColor.WHITE.index);
String format = getGridColumnXtypeFormat().get(gridColumnXtype);
if (StringUtils.isNotEmpty(format)) {
style.setDataFormat(createHelper.createDataFormat().getFormat(format));
}
return style;
}
private HSSFCellStyle getColumnHeaderStyle(HSSFWorkbook workbook) {
HSSFFont columnHeadFont = workbook.createFont();
columnHeadFont.setFontName("宋体");
columnHeadFont.setFontHeightInPoints((short) 10);
columnHeadFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
HSSFCellStyle columnHeadStyle = workbook.createCellStyle();
columnHeadStyle.setFont(columnHeadFont);
columnHeadStyle.setAlignment(CellStyle.ALIGN_CENTER);
columnHeadStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
columnHeadStyle.setLocked(true);
columnHeadStyle.setWrapText(true);
columnHeadStyle.setLeftBorderColor(HSSFColor.BLACK.index);
columnHeadStyle.setBorderLeft((short) 1);
columnHeadStyle.setRightBorderColor(HSSFColor.BLACK.index);
columnHeadStyle.setBorderRight((short) 1);
columnHeadStyle.setBorderBottom(CellStyle.BORDER_THIN);
columnHeadStyle.setBottomBorderColor(HSSFColor.BLACK.index);
columnHeadStyle.setFillForegroundColor(HSSFColor.WHITE.index);
return columnHeadStyle;
}
}
第三步 编写映射到excel表格的样式类
package com.xjpower.web.core.export;
import java.util.ArrayList;
import java.util.List;
/**
* 映射到ExtjsGrid的 Excel导出格式
*/
public class ExcelExtGrid {
public String fileId;
public String fileName;
/**
* 增加 Grid column
*
* @param header
* @param width
* @param dataIndex
*/
public void addGridColumn(String header, Integer width, String dataIndex, String xtype) {
GridColumn col = new GridColumn();
col.header = header;
col.width = width;
col.dataIndex = dataIndex;
col.xtype = xtype;
this.columns.add(col);
}
/**
* 表列布局
*/
public List<GridColumn> columns = new ArrayList<GridColumn>();
/**
* extjs grid的属性映射
*/
public static class GridColumn {
/**
* 列头
*/
public String header;
/**
* 列宽度
*/
public Integer width;
/**
* 访问值
*/
public String dataIndex;
/**
* 数据类型
*/
public String xtype;
}
}
第四步 编写Controller
@RequestMapping("outInRecord/exportList")
@ResponseBody
public ModelAndView exportList(String name) {
ExcelExportView excelExportView = null;
try {
int start = 0;
int limit = 2000;
ExcelExtGrid grid = new ExcelExtGrid();
grid.fileName = "员工责任表";
grid.addGridColumn("编号", 80, "ID", "gridcolumn");
grid.addGridColumn("名字", 80, "name", "gridcolumn");
grid.addGridColumn("责任", 80, "bility", "gridcolumn");
PageInfo<People> outInRecordDetailPageInfo = peopleService.SelectAll(name,start, limit);
excelExportView = new ExcelExportView(grid, outInRecordDetailPageInfo.getList());
} catch (Exception e) {
logger.error("OutInRecordController.exportList异常:", e);
}
return new ModelAndView(excelExportView);
}
第五步 js调用后端得到数据
$("#exportList").on('click', function (event) {
alert("ss");
window.location.href="outInRecord/exportList";
event.stopPropagation();
});