导入导出
获取文件路径
注意
打成jar包后,文件的磁盘绝对路径String,获取不到的话,换个思路,看看参数可以传流InputStream,或者Excel、doc的poi的原生对象不,可以的话,用resource.getInputStream()获取流
org.springframework.core.io.Resource resource =resourceLoader.getResource("classpath:/word/demo.docx");
InputStream is=resource.getInputStream();
MyXWPFDocument word = new MyXWPFDocument(is);
WordExportUtil.exportWord07(word,map);
完整示例:
点击查看代码
public void exportWord(Integer id, HttpServletResponse response) throws Exception {
// 这样拿的是当前模块的根路径
org.springframework.core.io.Resource resource =resourceLoader.getResource("classpath:/word/demo.docx");
log.info("getURL: {}", resource.getURL());
log.info("当前项目模板磁盘绝对路径: {}", resource.getURL().getPath());
log.info("getFilename: {}",resource.getFilename());
try(InputStream is=resource.getInputStream();){
MyXWPFDocument word = new MyXWPFDocument(is);
//随机生成单据编号
String djbh = UUID.randomUUID().toString();
//1.查出对应数据
Map<String,Object> map = new HashMap<>();
map.put("name", djbh);
//2.映射为模板
WordExportUtil.exportWord07(word,map);
String filename = "大货采购单.docx";
//导出
response.setHeader("content-disposition","attachment;filename="+new String(filename.getBytes(),"ISO8859-1"));
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
word.write(response.getOutputStream());
response.getOutputStream().flush();
response.getOutputStream().close();
}catch(IOException e){
log.error("读模板文件出现异常,文件路径:{}" ,e);
}
}
点击查看代码
String templateName = "jcwgxfwExportDemo.xls";
String templatePath = request.getSession().getServletContext().getRealPath("/")
+ File.separator + "exporttemp"+File.separator+templateName ;
下载的文件名乱码
转码代码
点击查看代码
String fileName = URLEncoder.encode("故障处置经过.doc", "utf-8");
response.setHeader("Content-disposition", "attachment; filename="+new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
html导出doc
注意点
- 推荐用jquery前端生成doc,码云有js文件
- 富文本生成doc,如果打开时弹窗提示:“转换文件”
office软件设置问题,如图取消勾选
controller
点击查看代码
/**
* 导出word
* @param id
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/exportWord")
@ResponseBody
public void exportWord(@RequestParam String id,HttpServletRequest request, HttpServletResponse response) throws Exception {
FaultRecord bean = faultRecordService.findById(FaultRecord.class, id);
Map<String, Object> map = new HashMap<String, Object>();
String filePath = ExcelUtil.getTempletFilePath(request, "Doc1.doc");
// 无需新增标签,其实是office"选项卡设置"问题
// String value = "<html>";
String value = "<html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <title>Title</title>\n</head>\n<body>\n";
value += Optional.ofNullable(bean).map(i -> i.getDisposal()).orElse("");
value += "</body>\n</html>";
map.put("disposal", value);
String URL = filePath;
File file = new File(URL);
PrintWriter out = null;
try {
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
response.setHeader("Content-disposition", "attachment; filename=03doc.doc");
out = response.getWriter();
out.println(value);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (out != null) {
out.flush();
out.close();
}
}
}
导入excel
下载模板
点击查看代码
response.setContentType("application/vnd.ms-excel;charset=gb2312");
response.addHeader("Content-Disposition",
"attachment;filename=" + new String(exportName.getBytes(), "ISO8859-1") + ".xls");
ServletOutputStream os = response.getOutputStream(); // 获得输出流
// 读取excel模板,输入流也可以关
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(demoPath));
wb.write(os);
os.flush();
os.close();
检查是否为空模板
- 坑:空表头的第一行看似空白,但程序会解析到一行。
- 思路:获取指定sheet的lastRowNum();这个是size,和模板的表头的行数比较;
- 如果表头下的行数据,判断是否为null,
点击查看代码
Object val = declaredField.get(bean);
if (val instanceof String) {
if (StringUtil.isNotBlank((String) val)) {
return false;
}
}
if (val != null) {
return false;
}
校验分组类型
点击查看代码
public class Group {
/**新增校验*/
public interface Add{}
/**删除校验*/
public interface Remove{}
/**修改校验*/
public interface Edit{}
/**导入校验*/
public interface Import extends Default {}
}
实体类注解校验
点击查看代码
@NotBlank(groups = {Group.Import.class},message = "所亭名称,不能为空;")
private String subName;
Service
- 步奏:1:检查是否为空
- 2:每行数据校验
- 3:根据判重字段,查询改行是否重复
用集合接受查询结果,可最大兼顾原来表中已重复数据 - 4:再根据导入重复处理规定,做跳过或覆盖
点击查看代码
@Resource
private javax.validation.Validator validator;
/**
* 注解方式校验数据合法性
* @param isAll 是否返回全部错误(true:是)
* @param validator 非spring的校验类
* @param model 实体对象
* @param groups 属性注解上按分组接口
* @param <T> 实体对象类
* @throws MessageException
*/
private<T> void check(boolean isAll,javax.validation.Validator validator, T model, Class<?>... groups) throws MessageException {
String msg = "";
Set<ConstraintViolation<T>> validate = validator.validate(model, groups);
for (ConstraintViolation<T> it : validate) {
if (isAll) {
msg += it.getMessage();
}else {
// 有错及中止
throw new MessageException(msg);
}
}
if(!"".equals(msg)){
throw new MessageException(msg);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】