1、导入org.apache.poi 包
2、工具类
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
/**
* excel工具类
*
*
*/
public class ExcelUtils {
/**
* Excel导出
*
* @param response response
* @param fileName 文件名
* @param list 数据List
* @param pojoClass 对象Class
*/
public static void exportExcel(HttpServletResponse response, String fileName, Collection<?> list,
Class<?> pojoClass) throws IOException {
final String DATE_PATTERN = "yyyy-MM-dd";
if(StringUtils.isBlank(fileName)){
//当前日期
fileName = format(new Date(),DATE_PATTERN);
}
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), pojoClass, list);
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xls");
ServletOutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
}
public static String format(Date date, String pattern) {
if(date != null){
SimpleDateFormat df = new SimpleDateFormat(pattern);
return df.format(date);
}
return null;
}
/**
* Excel导出,先sourceList转换成List<targetClass>,再导出
*
* @param response response
* @param fileName 文件名
* @param sourceList 原数据List
* @param targetClass 目标对象Class
*/
public static void exportExcelToTarget(HttpServletResponse response, String fileName, Collection<?> sourceList,
Class<?> targetClass) throws Exception {
List targetList = new ArrayList<>(sourceList.size());
for(Object source : sourceList){
Object target = targetClass.newInstance();
BeanUtils.copyProperties(source, target);
targetList.add(target);
}
exportExcel(response, fileName, targetList, targetClass);
}
}
3、需要导出数据的实体
@Data
@ApiModel(value = "导出Excel测试")
public class testExecelDTO {
@ApiModelProperty(value = "字段1")
private String test1;
@ApiModelProperty(value = "字段2")
private String test2;
private Date createDate;
}
4、需要导出数据的EXCEL实体
@Data
public class testExecel{
@Excel(name = "字段1")
private String test1;
@Excel(name = "字段2")
private String test2;
@Excel(name = "派单时间", exportFormat="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Date createDate;
}
5、调用
@GetMapping("export")
@ApiOperation("导出")
@LogOperation("导出")
public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
List<testExecelDTO> list = new ArrayList();
ExcelUtils.exportExcelToTarget(response, "文件导出", list, testExecel.class);
}