思路:
1,先创建动态模板(必须要在数据库建一张表,可随时修改模板)
例如:
建表语句:
CREATE TABLE `list_table_header` (
`headerName` VARCHAR(100) NOT NULL,
`headerField` VARCHAR(100) NOT NULL,
`headerType` VARCHAR(100) DEFAULT NULL,
`headerLength` VARCHAR(100) DEFAULT NULL,
`isModify` VARCHAR(50) DEFAULT 'true',
`isDelete` VARCHAR(50) DEFAULT 'true',
`isAuto` VARCHAR(50) DEFAULT 'false',
`id` INT(50) NOT NULL AUTO_INCREMENT,
`colExample` VARCHAR(1000) DEFAULT '非必填' COMMENT '样例',
PRIMARY KEY (`headerName`,`headerField`),
KEY `id` (`id`)
) ENGINE=INNODB AUTO_INCREMENT=511 DEFAULT CHARSET=utf8
模板中的字段脚本:
INSERT INTO list_table_header(headerName,headerField,headerType,headerLength,isModify,isDelete,isAuto,colExample) VALUES('序列','orderNo','int','20','false','false','false','系统自动计算(勿填)');
INSERT INTO list_table_header(headerName,headerField,headerType,headerLength,isModify,isDelete,isAuto,colExample) VALUES('月份','month','VARCHAR','200','false','false','false','必填项(如:2023-04)');
INSERT INTO list_table_header(headerName,headerField,headerType,headerLength,isModify,isDelete,isAuto,colExample) VALUES('单据编号','numberNo','VARCHAR','200','false','false','false','系统自动计算(勿填)');
INSERT INTO list_table_header(headerName,headerField,headerType,headerLength,isModify,isDelete,isAuto,colExample) VALUES('部门A','hrA','VARCHAR','200','false','false','false','必填项(如:123)');
INSERT INTO list_table_header(headerName,headerField,headerType,headerLength,isModify,isDelete,isAuto,colExample) VALUES('部门B','hrB','VARCHAR','200','false','false','false','必填项(如:456)');
INSERT INTO list_table_header(headerName,headerField,headerType,headerLength,isModify,isDelete,isAuto,colExample) VALUES('部门C','hrC','VARCHAR','200','false','false','false','必填项(如:789)');
INSERT INTO list_table_header(headerName,headerField,headerType,headerLength,isModify,isDelete,isAuto,colExample) VALUES('部门D','hrD','VARCHAR','200','false','false','false','必填项(如:897)');
2,编写一个查询接口:返回一个List map
注意:order by id 根据表中字段:id排序的作用是控制导出的EXCEL表中字段列的顺序;
mapper.xml层:
<!-- 查询:动态模板 -->
<select id="query" resultType="map">
select * from bcg_question_list_table_header
order by id
</select>
mapper接口层:
//查询:动态模板
List<Map<String, Object>> query();
serviceImpl层:
@Autowired
private HeimaListMapper heimaListMapper;
/*
* 查询:数据导出动态模板
*/
private List<Map<String, Object>> getHeaderss_1() {
List<Map<String, Object>> kk = heimaListMapper.query();
// 导出模板不需要:hrC,hrD这两个字段,过滤掉;
kk = kk.stream().filter(e -> (!e.get("headerField").equals("hrC"))).
filter(e -> (!e.get("headerField").equals("hrD"))).
collect(Collectors.toList());
return kk;
}
ok,到此我们前两步就完成了,成功获取到了模板表中的数据!
3,编写接口,将拿到的模板数据写入EXCEL
Controller层:
/**
* 下载:动态模板
* 权限-管理员
*
* @param response
* @return
*/
@PostMapping(value = "/downFormDataTemplete")
@AuthInterceptor("mag:down:FormDataTemplete") // 资源项
public Result downFormDataTemplete(HttpServletResponse response) {
try {
questionListService.downFormDataTemplete(response);
} catch (Exception e) {
log.error("===模板下载 downnFormDataTemplete is error===:" + e.getMessage(), e);
return CommonUtil.getErrorInfo("服务异常,模板下载失败!");
}
return Result.success().result("下载模板成功");
}
service接口层:
//下载:动态模板
void downFormDataTemplete(HttpServletResponse response) throws IOException;
serviceImpl实现层:
/*
*下载:获取导出动态模板
*
*/
@Override
public void downFormDataTemplete(HttpServletResponse response) throws IOException {
// 把前两步获取到的数据:getHeaderss_1带入
List<List<String>> cells = getTemplateHeaders(getHeaderss_1());
// 获取sheetName
String sheetName = "表单数据";
// 更新excel模板
ExcelUtil.downExcel(response, "模板XXX",
cells, sheetName, getExcelTemplateDatas(getHeaderss_1()));
}
/**
* 获取模板表头信息
*
* @param headers
* @return
*/
public static List<List<String>> getTemplateHeaders(List<Map<String, Object>> headers) {
List<List<String>> cells = new ArrayList<List<String>>();
for (Map<String, Object> header : headers) {
List<String> headerList = new ArrayList<String>();
headerList.add(header.get("headerName").toString());
cells.add(headerList);
}
return cells;
}
/**
* 查询:获取模板数据
*
*/
private List<List<String>> getExcelTemplateDatas(List<Map<String, Object>> headers) {
List<List<String>> datas = new ArrayList<>();
List<String> data = new ArrayList<>();
for (Map<String, Object> header : headers) {
data.add(header.get("colExample") != null ?
header.get("colExample").toString() : "");
}
datas.add(data);
return datas;
}
Excel导出工具类:
package com.itheima.service.common.util;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.itheima.service.common.entity.CellsFieldDefine;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class ExcelUtil {
public static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
/**
* 读取Excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是第几行
*
* @param in 读取数据的源Excel
* @param ignoreRows 读取数据忽略的行数,比喻行头不需要读入 忽略的行数为1
* @return 读出的Excel中数据的内容
* @throws IOException 异常
*/
public static String[][] getXlsxData(InputStream in, int ignoreRows)
throws IOException {
List<String[]> result = new ArrayList<String[]>();
int rowSize = 0;
XSSFWorkbook wb = new XSSFWorkbook(in);
XSSFCell cell = null;
for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
XSSFSheet st = wb.getSheetAt(sheetIndex);
// 第一行为标题,取标题值
for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
XSSFRow row = st.getRow(rowIndex);
if (row == null) {
continue;
}
int tempRowSize = row.getLastCellNum();
if (tempRowSize > rowSize) {
rowSize = tempRowSize;
}
String[] values = new String[rowSize];
Arrays.fill(values, "");
boolean hasValue = false;
for (short columnIndex = 0; columnIndex < row.getLastCellNum(); columnIndex++) {
String value = "";
cell = row.getCell(columnIndex);
if (cell != null) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue().trim();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
value = getString(HSSFDateUtil.isCellDateFormatted(cell), cell.getDateCellValue(), cell
.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA:
// 导入时如果为公式生成的数据则无值
if (!"".equals(cell.getStringCellValue())) {
value = cell.getStringCellValue();
} else {
value = cell.getNumericCellValue() + "";
}
break;
case HSSFCell.CELL_TYPE_BLANK:
break;
case HSSFCell.CELL_TYPE_ERROR:
value = "";
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
value = (cell.getBooleanCellValue() ? "Y" : "N");
break;
default:
value = "";
}
}
if (columnIndex == 0 && "".equals(value.trim())) {
break;
}
value = value.trim();
values[columnIndex] = rightTrim(value);
hasValue = true;
//System.out.println(value + ":" + columnIndex);
}
if (hasValue) {
result.add(values);
}
}
}
return getStrings(in, result, rowSize);
}
public static String[][] getXlsData(InputStream in, int ignoreRows) throws IOException {
List<String[]> result = new ArrayList<String[]>();
int rowSize = 0;
// 打开HSSFWorkbook
POIFSFileSystem fs = new POIFSFileSystem(in);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFCell cell;
for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
HSSFSheet st = wb.getSheetAt(sheetIndex);
// 第一行为标题,不取
for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
HSSFRow row = st.getRow(rowIndex);
if (row == null) {
continue;
}
int tempRowSize = row.getLastCellNum();
if (tempRowSize > rowSize) {
rowSize = tempRowSize;
}
String[] values = new String[rowSize];
Arrays.fill(values, "");
boolean hasValue = false;
for (short columnIndex = 0; columnIndex < row.getLastCellNum(); columnIndex++) {
String value = "";
cell = row.getCell(columnIndex);
if (cell != null) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
value = getString(HSSFDateUtil.isCellDateFormatted(cell), cell.getDateCellValue(), cell
.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA:
// 导入时如果为公式生成的数据则无值
if (!cell.getStringCellValue().equals("")) {
value = cell.getStringCellValue();
} else {
value = cell.getNumericCellValue() + "";
}
break;
case HSSFCell.CELL_TYPE_BLANK:
break;
case HSSFCell.CELL_TYPE_ERROR:
value = "";
System.out.println(value + ":" + columnIndex);
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
value = (cell.getBooleanCellValue() == true ? "Y" : "N");
break;
default:
value = "";
}
}
if (columnIndex == 0 && "".equals(value.trim())) {
break;
}
value = value.trim();
values[columnIndex] = rightTrim(value);
hasValue = true;
}
if (hasValue) {
result.add(values);
}
}
}
return getStrings(in, result, rowSize);
}
public static StringBuilder getStringMessage(List<String> list) {
StringBuilder message = new StringBuilder();
for (int i = 0, listSize = list.size(); i < listSize; i++) {
String str = list.get(i);
if (i == listSize - 1 && listSize > 1) {
message.append("[").append(str).append("]字段!");
} else if (i == 0 && listSize > 1) {
message.append("Excel表头无[").append(str).append("],");
} else if (i == 0) {
message.append("Excel表头无[").append(str).append("]字段!");
} else {
message.append("[").append(str).append("],");
}
}
return message;
}
private static String rightTrim(String str) {
if (str == null) {
return "";
}
int length = str.length();
for (int i = length - 1; i >= 0; i--) {
if (str.charAt(i) != 0x20) {
break;
}
length--;
}
return str.substring(0, length);
}
private static String[][] getStrings(InputStream in,
List<String[]> result, int rowSize) throws IOException {
in.close();
String[][] returnArray = new String[result.size()][rowSize];
for (int i = 0; i < returnArray.length; i++) {
returnArray[i] = result.get(i);
}
return returnArray;
}
private static String getString(boolean cellDateFormatted,
Date dateCellValue, double numericCellValue) {
String value;
if (cellDateFormatted) {
Date date = dateCellValue;
if (date != null) {
value = new SimpleDateFormat("yyyy-MM-dd")
.format(date);
} else {
value = "";
}
} else {
value = new DecimalFormat("#.#").format(numericCellValue);
}
return value;
}
public static void downExcel(HttpServletResponse response, String fileName,
List<List<String>> headers, String sheetName,
List<List<String>> datas) throws IOException {
//设置MIME类型,用于指定文件的内容类型,具体来说,这个类型是用于表示EXCEL电子表格文件
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");// 设置字符编码
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx"); // 设置响应头
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).head(headers)
.registerWriteHandler(getCellStyle())
.autoCloseStream(Boolean.TRUE)
.build();
int sheetNum = 0;
WriteSheet writeSheet = EasyExcel.writerSheet(sheetNum, sheetName).build();
// 写入文件
excelWriter.write(datas, writeSheet);
// 关闭文件流
excelWriter.finish();
}
private static HorizontalCellStyleStrategy getCellStyle() {
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//垂直居中,水平居中
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
//背景设置白色
contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE1.getIndex());
//设置 自动换行
contentWriteCellStyle.setWrapped(true);
// 字体策略
WriteFont contentWriteFont = new WriteFont();
// 字体大小
contentWriteFont.setFontHeightInPoints((short) 12);
contentWriteFont.setColor(IndexedColors.GREY_25_PERCENT.getIndex());
contentWriteCellStyle.setWriteFont(contentWriteFont);
// 头样式
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setFillForegroundColor(IndexedColors.YELLOW1.index);
WriteFont headWriteFont = new WriteFont();
headWriteFont.setBold(true);
headWriteFont.setFontName("宋体");
headWriteFont.setFontHeightInPoints((short) 11);
headWriteCellStyle.setWriteFont(headWriteFont);
return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
}
/**
* 处理字段的表头值
*
* @param headMap
* @return
*/
public static List<String> createdHead(String[] headMap) {
List<String> list = new ArrayList<String>();
for (String head : headMap) {
list.add(head);
}
return list;
}
public static void uploadExcel(HttpServletResponse response, String fileName,
List<String> columnList, List<List<Object>> dataList) throws Exception {
//声明输出流
OutputStream os = null;
//设置响应头
setResponseHeader(response, fileName);
try {
//获取输出流
os = response.getOutputStream();
//内存中保留1000条数据,以免内存溢出,其余写入硬盘
SXSSFWorkbook wb = new SXSSFWorkbook(1000);
//获取该工作区的第一个sheet
Sheet sheet1 = wb.createSheet(fileName);
int excelRow = 0;
//创建标题行
Row titleRow = sheet1.createRow(excelRow++);
for (int i = 0; i < columnList.size(); i++) {
//创建该行下的每一列,并写入标题数据
Cell cell = titleRow.createCell(i);
cell.setCellValue(columnList.get(i));
}
//设置内容行
if (dataList != null && dataList.size() > 0) {
//序号是从1开始的
int count = 1;
//外层for循环创建行
for (int i = 0; i < dataList.size(); i++) {
Row dataRow = sheet1.createRow(excelRow++);
//内层for循环创建每行对应的列,并赋值
for (int j = 0; j < dataList.get(0).size(); j++) {//由于多了一列序号列所以内层循环从-1开始
Cell cell = dataRow.createCell(j);
if (dataList.get(i).get(j) != null) {
cell.setCellValue(dataList.get(i).get(j).toString());
}
}
}
}
//将整理好的excel数据写入流中
wb.write(os);
} catch (IOException e) {
logger.error("===上传清单方法(uploadChecklist) is error===:" + e.getMessage());
throw e;
} finally {
try {
// 关闭输出流
if (os != null) {
os.close();
}
} catch (IOException e) {
logger.error("===上传清单方法(uploadChecklist) is error===:" + e.getMessage());
throw e;
}
}
}
/*
设置浏览器下载响应头
*/
private static void setResponseHeader(HttpServletResponse response, String fileName) throws Exception {
try {
fileName = new String(fileName.getBytes("UTF-8"), "UTF-8");
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
logger.error("===上传清单方法(uploadChecklist) is error===:" + ex.getMessage());
throw ex;
}
}
/*
* 导出模板清单回填数据(无序列号):
*
*/
public static void getWriteDatas(HttpServletResponse response,
List<Map<String, Object>> datas, List<Map<String, Object>> headers,
String fileName) throws Exception {
List<CellsFieldDefine> fList = new ArrayList<CellsFieldDefine>();
for (Map<String, Object> header : headers) {
CellsFieldDefine cellsFieldDefine = new CellsFieldDefine();
cellsFieldDefine.setFieldKey(header.get("headerField").toString());
cellsFieldDefine.setFieldCnName(header.get("headerName").toString());
fList.add(cellsFieldDefine);
}
String[] arry = new String[fList.size()];
for (int i = 0; i < fList.size(); i++) {
arry[i] = fList.get(i).getFieldKey();
}
String[] headArry = new String[fList.size()];
for (int i = 0; i < fList.size(); i++) {
headArry[i] = fList.get(i).getFieldCnName();
}
List<List<Object>> dataList = new ArrayList<List<Object>>();
for (Map<String, Object> m : datas) {
List<Object> data = new ArrayList<Object>();
for (int i = 0; i < arry.length; i++) {
data.add(m.get(arry[i]));
}
dataList.add(data);
}
uploadExcel(response, fileName, ExcelUtil.createdHead(headArry), dataList);
}
/*
* 导出模板清单回填数据,并且首列加入序列号:
*
*/
public static void getWriteDatas2(HttpServletResponse response,
List<Map<String, Object>> datas, List<Map<String, Object>> headers,
String fileName) throws Exception {
List<CellsFieldDefine> fList = new ArrayList<CellsFieldDefine>();
for (Map<String, Object> header : headers) {
CellsFieldDefine cellsFieldDefine = new CellsFieldDefine();
cellsFieldDefine.setFieldKey(header.get("headerField").toString());
cellsFieldDefine.setFieldCnName(header.get("headerName").toString());
fList.add(cellsFieldDefine);
}
String[] arry = new String[fList.size()];
for (int i = 0; i < fList.size(); i++) {
arry[i] = fList.get(i).getFieldKey();
}
String[] headArry = new String[fList.size()];
for (int i = 0; i < fList.size(); i++) {
headArry[i] = fList.get(i).getFieldCnName();
}
List<List<Object>> dataList = new ArrayList<List<Object>>();
//与getWriteDatas不同之处:
for (int i = 0; i < datas.size(); i++) {
List<Object> data = new ArrayList<Object>();
for (int j = 0; j < arry.length; j++) {
//首列为序号列:
if(j == 0){
data.add(i+1);
}
//首列之后回填数据
if (j > 0) {
data.add(datas.get(i).get(arry[j]));
}
}
dataList.add(data);
}
uploadExcel(response, fileName, ExcelUtil.createdHead(headArry), dataList);
}
}
到此,模板导出就完成了!
需注意:这种二进制流形式的导出一般是前端给导出模板命名哈!