easyPoi处理文件下载文件名为空问题----请求头信息
程序员文章站
2022-03-15 12:57:48
...
导包:同上一篇导出封装请求参数
定义注解:
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import java.lang.annotation.*;
/**
* 导出Excel注解.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ExportExcel {
// 导出文件名.
String fileName();
// Excel类型.默认03、07格式.
ExcelType excelType() default ExcelType.HSSF;
}
定义切面方法:匹配注解进行切面环绕设置请求头信息
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.ahies.system.sso.annotation.ExportExcel;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
/**
* 导出Excel切面.
*
* @author Hohn
*/
@Aspect
@Order
@Component
public class ExcelExportAspect {
@Around(value = "@annotation(excel)")
public Object processTx(ProceedingJoinPoint joinPoint, ExportExcel excel)
throws Throwable {
Object[] args = joinPoint.getArgs();
// Http请求.
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// Http响应.
HttpServletResponse response = null;
// 最终的文件名(处理中文兼容问题).
String finalFileName = excel.fileName();
// 文件后缀名.
String suffix = excel.excelType().equals(ExcelType.HSSF) ? ".xls" : ".xlsx";
for (int i = 0; i < args.length; i++) {
final String userAgent = request.getHeader("USER-AGENT");
// IE浏览器(IE11特殊处理).
if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "rv:11")) {
finalFileName = URLEncoder.encode(excel.fileName(), "UTF8");
}
// Google,火狐浏览器
else if (StringUtils.contains(userAgent, "Mozilla")) {
finalFileName = new String(excel.fileName().getBytes(), "ISO8859-1");
}
// 其他浏览器.
else {
finalFileName = URLEncoder.encode(excel.fileName(), "UTF8");
}
if (args[i] instanceof HttpServletResponse) {
response = (HttpServletResponse) args[i];
// 告诉浏览器用什么软件可以打开此文件.
response.setHeader("content-Type", "application/vnd.ms-excel");
// 下载文件的默认名称.
response.setHeader("Content-Disposition", "attachment;filename=" + finalFileName + suffix);
// 编码.
response.setCharacterEncoding("UTF-8");
}
}
Object result = null;
try {
result = joinPoint.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
return result;
}
}