@Slf4j
public class ExcelUtils {
/**
*
* @param fileName 文件名称
* @param clazz 字段描述
* @param data 写入值
* @param response 返回结果
*/
public static void exportExcel(String fileName, Class clazz, List<?> data, HttpServletResponse response) throws Exception {
ExcelWriter writer = ExcelUtil.getWriter(true);
writer.setOnlyAlias(true);
// 获取当前类字段
Field[] fields = clazz.getDeclaredFields();
setAlias(writer,data,clazz,fields);
writer.write(data, true);
//设置宽度自适应
setSizeColumn(writer.getSheet(),fields.length);
//设置样式
setStyle(writer);
final OutputStream output = response.getOutputStream();
try {
// 获取我们的输出流
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8")+".xls");
writer.flush(output, true);
log.info("报表导出成功");
} catch (Exception e) {
log.error("报表导出失败:", e);
}finally {
writer.close();
IoUtil.close(output);
}
}
/**
* 设置表头
* @param writer
* @param clazz
* @param fields
*/
public static void setAlias(ExcelWriter writer, List<?> data,Class clazz,Field[] fields) throws Exception {
if (!data.get(0).getClass().equals(clazz)) {
log.error("数据类型与传入的数据类型不匹配!数据类型:{},几何数据类型:{}");
throw new Exception("数据类型与传入的集合数据类型不一致!");
}else{
for (Field field : fields) {
// 设置访问属性
if (!field.isAccessible()) {
field.setAccessible(true);
}
/**
* 此处判断需要导出的字段方式是使用的excel的注解作为依据
* 如果项目中未使用excel的注解,可以自定义注解作为依据或者能够作为判断依据的相关表示
**/
boolean annotationPresent = field.isAnnotationPresent(Excel.class);
if (annotationPresent) {
Excel annotation = field.getAnnotation(Excel.class);
//获取字段值
String key = field.getName();
// 获取注解的值作为导出的表头
String value = annotation.name();
writer.addHeaderAlias(key,value);
}
}
}
}
/**
* 自适应宽度(中文支持)
*
* @param sheet sheet
* @param size 因为for循环从0开始,size值为 列数-1
*/
public static void setSizeColumn(Sheet sheet, int size) {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
for (int columnNum = 0; columnNum <= size; columnNum++) {
int columnWidth = sheet.getColumnWidth(columnNum) / 256;
for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(columnNum) != null) {
Cell currentCell = currentRow.getCell(columnNum);
if (currentCell.getCellType() == CellType.STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length) {
columnWidth = length;
}
}else if (currentCell.getCellType() == CellType.NUMERIC){
//判断是否是日期格式
if (DateUtil.isCellDateFormatted(currentCell)) {
LocalDateTime localDateTimeCellValue = currentCell.getLocalDateTimeCellValue();
String format = df.format(localDateTimeCellValue);
columnWidth=format.length();
}else{
double numericCellValue = currentCell.getNumericCellValue();
int length = String.valueOf(numericCellValue).getBytes().length;
if (columnWidth < length) {
columnWidth = length;
}
}
}
}
sheet.setColumnWidth(columnNum, columnWidth * 300);
}
}
public static void setStyle(ExcelWriter writer) {
StyleSet style = writer.getStyleSet();
CellStyle cellStyle = style.getCellStyle();
cellStyle.setWrapText(false);
//设置标题头样式
CellStyle headCellStyle = style.getHeadCellStyle();
headCellStyle.setAlignment(HorizontalAlignment.CENTER);
//设置内容字体
Font font = writer.createFont();
//加粗
font.setBold(true);
//设置标题字体大小
font.setFontHeightInPoints((short) 12);
font.setFontName("微软雅黑");
headCellStyle.setFont(font);
}
}
Hutool工具类导出excel
最新推荐文章于 2024-09-06 15:09:00 发布