使用poi插件封装,直接上代码:
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CommonExcelUtil<T> {
@Autowired
private static EncryptUtil encryptUtil;
public void setUpExcel(HttpServletResponse response, String table, List list, String fileName) throws IOException {
String[] tables = table.split(",");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
//设置列宽
sheet.setDefaultColumnWidth((short) 18);
//创建第一行的对象,第一行一般用于填充标题内容。从第二行开始一般是数据
XSSFRow row = sheet.createRow(0);
for (short i = 0; i < tables.length; i++) {
//创建单元格,每行多少数据就创建多少个单元格
XSSFCell cell = row.createCell(i);
XSSFRichTextString text = new XSSFRichTextString(tables[i].substring(0, tables[i].indexOf("(")));
//给单元格设置内容
cell.setCellValue(text);
}
inputStr(sheet, row, list, fileName, tables);
response.setContentType("application/vnd..ms-excel");
response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xlsx");//Excel文件名
try {
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
//将workbook中的内容写入输出流中
workbook.write(response.getOutputStream());
}
private void inputStr(XSSFSheet sheet, XSSFRow row, List list, String fileName, String[] tables) {
List<T> customerList = list;
//遍历集合,将每个集合元素对象的每个值填充到单元格中
for (int i = 0; i < customerList.size(); i++) {
T statisticsModel = customerList.get(i);
//从第二行开始填充数据
row = sheet.createRow(i + 1);
//该集合只记录数量和时间,这两个值来自statisticsModel。如果对象比较复杂,需要额外转换,比如Date类型的日期,int,float类型的数值
List<String> dataList = new ArrayList<>();
Class<?> clz = statisticsModel.getClass();
for (String table : tables) {
String fieldName = table.substring(table.indexOf("(") + 1, table.indexOf(")"));
String methodName = "get" + String.valueOf(fieldName.charAt(0)).toUpperCase() + fieldName.substring(1, fieldName.length());
try {
dataList.add(String.valueOf(clz.getMethod(methodName, null).invoke(statisticsModel)));
} catch (Exception e) {
e.printStackTrace();
}
}
ExcelOut(dataList, row);
}
}
/**
* 数据导入
*/
private static void ExcelOut(List<String> dataList, XSSFRow row) {
for (int j = 0; j < dataList.size(); j++) {
String str = dataList.get(j);
XSSFCell cell = row.createCell(j);
XSSFRichTextString richString = new XSSFRichTextString(str);
cell.setCellValue(richString);
}
}
}
调用代码:
//传入列title和对应的取值属性名
params.setTableTitle("客户姓名(customerName),年龄(age),性别(sex),业务员(salesman),注册时间(registDate)");
customerService.printExcel(params, response);
---------------------------------------------------------------
try {
CommonExcelUtil<CustomerResultModel> excelUtil = new CommonExcelUtil<>();
excelUtil.setUpExcel(response, param.getTableTitle(), customers, param.getFileName());
} catch (IOException e) {
log.error("导出客户信息列表excel异常", e);
e.printStackTrace();
}