导出excel
jra包
<!-- hutool工具包 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.1</version>
</dependency>
<!-- Excel包 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
1.ExcelByHuTools 工具代码
package com.user.service.dguser.uilt.excel;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.user.service.dguser.config.ExportField;
import com.user.service.dguser.uilt.RefUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.SheetUtil;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class ExcelByHuTools {
public static <T> ExcelWriter exportExcelByHuTools(Class<T> pojo,
List<T> data, String sheetName) throws InstantiationException, IllegalAccessException {
Map<String, String> headers = getFieldAnnotation(pojo);
return exportExcelByHuTools(headers, data, sheetName);
}
public static <T> ExcelWriter exportExcelByHuTools(Map<String, String> headers,
List<T> data, String sheetName) {
long startTime = System.currentTimeMillis();
try {
ExcelWriter writer = ExcelUtil.getBigWriter();
writer.renameSheet(sheetName);
headers.forEach(writer::addHeaderAlias);
writer.write(data, true);
CellStyle headCellStyle = writer.getHeadCellStyle();
Font font = createFont(writer, true, false, "宋体", 18);
headCellStyle.setFont(font);
Font font1 = createFont(writer, false, false, "宋体", 14);
setBaseGlobalStyle(writer, font1);
int columnCount = writer.getColumnCount();
for (int i = 0; i < columnCount; ++i) {
double width = SheetUtil.getColumnWidth(writer.getSheet(), i, false);
if (width != -1.0D) {
width *= 256.0D;
width += 220D;
writer.setColumnWidth(i, Math.toIntExact(Math.round(width / 256D)));
}
}
log.info("写入记录耗时:[{}]ms", System.currentTimeMillis() - startTime);
return writer;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Font createFont(ExcelWriter writer, boolean bold, boolean italic, String fontName, int fontSize) {
Font font = writer.getWorkbook().createFont();
font.setFontName(fontName);
font.setItalic(italic);
font.setFontHeightInPoints((short) fontSize);
font.setBold(bold);
return font;
}
public static StyleSet setBaseGlobalStyle(ExcelWriter writer, Font font) {
StyleSet styleSet = writer.getStyleSet();
styleSet.setAlign(HorizontalAlignment.CENTER, VerticalAlignment.CENTER);
styleSet.setFont(font, true);
styleSet.setBackgroundColor(IndexedColors.WHITE, false);
styleSet.setWrapText();
styleSet.setBorder(BorderStyle.THIN, IndexedColors.BLACK);
return styleSet;
}
public static void export(HttpServletRequest request, HttpServletResponse response, ExcelWriter writer, String filename) throws IOException {
setResponseHeader(request, response, filename);
ServletOutputStream out = response.getOutputStream();
writer.flush(out, true);
writer.close();
IoUtil.close(out);
}
public static void setResponseHeader(HttpServletRequest request, HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
response.setContentType("application/octet-stream;charset=UTF-8");
String finalFileName = fileName;
String userAgent = request.getHeader("user-agent");
if (userAgent != null && userAgent.indexOf("Firefox") >= 0 || userAgent.indexOf("Chrome") >= 0 || userAgent.indexOf("Safari") >= 0) {
finalFileName = new String((fileName).getBytes(), "ISO8859-1");
} else {
finalFileName = URLEncoder.encode(fileName, "UTF8");
}
response.setHeader("Content-Disposition", "attachment;filename=".concat(finalFileName));
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
}
public static Map<String, String> getFieldAnnotation(Class<?> pojo) throws IllegalAccessException, InstantiationException {
Object object = pojo.newInstance();
Field[] fields = object.getClass().getDeclaredFields();
Map<String, String> resultMap = new LinkedHashMap<>();
for (Field field : fields) {
boolean bool = field.isAnnotationPresent(ExportField.class);
if (bool) {
String value = field.getAnnotation(ExportField.class).value();
resultMap.put(field.getName(), value);
}
}
return resultMap;
}
}
2.自定义注解
package com.user.service.dguser.config;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface ExportField {
String value() default "";
int type() default 0;
}
3.实体类
package com.user.service.dguser.model;
import com.user.service.dguser.config.ExportField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User2 {
@ExportField(value = "学号")
private String deptId;
@ExportField(value = "姓名")
private String name;
@ExportField(value = "手机号")
private String phone;
@ExportField(value = "图像")
private String avatar;
@ExportField(value = "创建时间")
private Date createdTime;
}
4.测试
package com.user.service.dguser.controller;
import cn.hutool.poi.excel.ExcelWriter;
import com.user.service.dguser.model.User2;
import com.user.service.dguser.uilt.excel.ExcelByHuTools;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
@RestController
@RequestMapping("test")
public class ExcelOutController {
@Value("${Excel.path:dd}")
private String path;
@GetMapping("export")
public void export1(HttpServletRequest request, HttpServletResponse response) throws IOException {
List<User2> list = new ArrayList<>();
list.add(new User2("001", "小三", "13411112222", "三根毛", new Date()));
list.add(new User2("002", "小四", "13411112222", "三根毛", new Date()));
list.add(new User2("003", "", "13411112222", "三根毛", new Date()));
list.add(new User2("004", "小六", "", "三根毛", new Date()));
list.add(new User2("", "", "", "小七三根毛大家啊嘎啊噶跟家里刚啊刚来", new Date()));
list.add(new User2("006", "小八", "13411112222", "三根毛", new Date()));
try {
ExcelWriter writer = ExcelByHuTools.exportExcelByHuTools(User2.class, list, "sheet1");
ExcelByHuTools.export(request, response, writer, "dgzhang.xlsx");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
测试结果