效果
流程
- 设置列名
- 放入数据
- 设置一下response
- 回写
代码
package cn.mb.excelexport.util;
import cn.hutool.poi.excel.ExcelWriter;
import cn.mb.excelexport.annotation.ExportField;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.List;
public class ExportUtil {
public static <T> void exportExcel(Class<T> cls, List<T> rows, String fileName, String title, ExcelWriter writer,
HttpServletRequest request, HttpServletResponse response) throws IOException {
int totalColumn = 0;
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
ExportField annotation = field.getDeclaredAnnotation(ExportField.class);
if (annotation == null) continue;
writer.addHeaderAlias(field.getName(), annotation.desc());
totalColumn++;
}
writer.merge(totalColumn, title);
writer.write(rows, true);
String suffix = writer.isXlsx() ? ".xlsx" : ".xls";
fileName = fileName + suffix;
try {
String agent = request.getHeader("USER-AGENT");
if (null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident") || null != agent && -1 != agent.indexOf("Edge")) {
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} else if (null != agent && -1 != agent.indexOf("Mozilla")) {
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
}
} catch (Exception e) {
e.printStackTrace();
}
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setContentType("application/ms-excel;charset=utf-8");
OutputStream out = response.getOutputStream();
writer.flush(out);
writer.close();
out.close();
}
}
package cn.mb.excelexport.annotation;
import java.lang.annotation.*;
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExportField {
String desc();
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--hutool工具包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.1</version>
</dependency>
<!--poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
小结
上面工具类通过反射配置Excel的列名,且通过泛型来保证数据传递,其中通过注解方式
来标记字段(后续可在该注解上添加其他功能),使用者只需要传递所需数据,即可向前端
回写二进制流。
get请求下载好实现,但post带参请求下载,在向前端返回二进制流后,不知道前端如何
处理,如果有知道的兄弟可以教学一波!!
目前项目中就是通过url带token的方式来携带登录token,在拦截器中判断多了一层判断
demo
学习
设置列宽
postman测试下载