add: 增加excel导入帮助类

This commit is contained in:
wuy 2020-07-01 14:13:58 +08:00
parent f6711c3ce2
commit b71a687d9c
1 changed files with 36 additions and 0 deletions

View File

@ -26,7 +26,10 @@ import com.diboot.file.excel.listener.DynamicHeadExcelListener;
import com.diboot.file.excel.listener.FixedHeadExcelListener; import com.diboot.file.excel.listener.FixedHeadExcelListener;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.io.File; import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -114,6 +117,39 @@ public class ExcelHelper {
} }
} }
/**
* web 导出excel
*
* @param response
* @param clazz 导出的类
* @param data 导出的数据
* @param <T>
* @throws Exception
*/
public static <T extends BaseExcelModel> void exportExcel(HttpServletResponse response, String fileName,Class<T> clazz, List<T> data) throws Exception{
try {
response.setContentType("application/x-msdownload");
response.setCharacterEncoding("utf-8");
fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
response.setHeader("filename", fileName);
response.setHeader("err-code", String.valueOf(Status.OK.code()));
response.setHeader("err-msg", URLEncoder.encode("操作成功", StandardCharsets.UTF_8.name()));
// 这里需要设置不关闭流
EasyExcel.write(response.getOutputStream(), clazz)
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
.autoCloseStream(Boolean.FALSE)
.sheet("sheet1")
.doWrite(data);
} catch (Exception e) {
log.error("下载文件失败:", e);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.setHeader("err-code", String.valueOf(Status.FAIL_OPERATION.code()));
response.setHeader("err-msg", URLEncoder.encode("下载文件失败", StandardCharsets.UTF_8.name()));
}
}
private static File getExcelFile(String filePath){ private static File getExcelFile(String filePath){
File file = new File(filePath); File file = new File(filePath);
if(!file.exists()){ if(!file.exists()){