当前位置:网站首页>Internship: Upload method for writing excel sheet (import)
Internship: Upload method for writing excel sheet (import)
2022-08-03 23:23:00 【ahyo】
After the framework of the entire project is built,For programmers, you only need to start writing the business.比如一般的excel表的导入导出.such as personnelexcel表的导入导出.
以下是导入(把excelData upload realizes data interaction with the database):
It needs to be based on database tables and excelThe table corresponds to the construction of the class,Similar to the following writing form
public class governmentsModel extends Model<governmentsModel> {
private static long serialVersionUID=1L;
@TableField(value = "id",type= IdType.AUTO)
private Integer id;
/** *...... */
@Excel(name = "",width =25 )
@TableField("name")
@ApiModelProperty(value = "")
private String name;
/** *...... */
@Excel(name = "",width =25 )
@TableField("code")
@ApiModelProperty(value = "")
private String code;
/** * */
@TableField("type")
private Integer type;
/** *.... */
@Excel(name = "",width =50 )
@TableField("gb")
@ApiModelProperty(value = "")
private String gb;
/** *..... */
@Excel(name = "",width =50 )
@TableField("category_code")
@ApiModelProperty(value = "")
private String category_code;
....................
}
@excelThe annotations are correspondingexcelThe fields in the table are easy to formexcel表.
After the class is built,Make the write upload method,如下:
/** * 上传人员excel * * @param file * @return */
@RequestMapping(value = "/uploadExcel", method = RequestMethod.POST)
public ResponseData uploadExcel(HttpServletRequest request, MultipartFile file) {
ImportParams importParams = new ImportParams();
importParams.setTitleRows(1);
List<governmentsModel> result;
try {
result = ExcelImportUtil.importExcel(file.getInputStream(), governmentsModel.class, importParams);
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException(500, "表格导入错误!");
}
//保存员工信息
if (ToolUtil.isEmpty(result)) {
throw new BusinessException(BizExceptionEnum.EXCEL_EMPTY);
}
List<governmentsModel> errorList = employerService.importExcel(result);
request.getSession().setAttribute("employerList", errorList);
return new ResponseData<>(errorList.size() == 0);
}
Read the code snippet line by line:
1、methodtaken naturallypost Because it is imported, it needs to be uploadedexcel表,ResponseDataThe class is for the convenience of unifying the data format of the front and back ends.
2、HttpServletRequest request, MultipartFile file 是上传excel表时 The necessary parameters for the method request意为请求——服务器请求对象 .MultipartFile——MultipartFile是SpringMVC提供简化上传操作的工具类.
在不使用框架之前,都是使用原生的HttpServletRequest来接收上传的数据,文件是以二进制流传递到后端的,然后需要我们自己转换为File类.使用了MultipartFile工具类之后,我们对文件上传的操作就简便许多了.
3、ImportParams Chinese translation into import parameters 配合 importParams.setTitleRows(1) The number of rows occupied by the header is by default1,Represents that the title occupies one line
4、用集合存储excel表数据,try catch异常捕获 通过ExcelImportUtil工具类 Call the import method——importExcel Pass in file input stream parameters、Use the reflection mechanism to obtain the corresponding base database table sumexcelThe number of rows occupied by the class parameters and headers corresponding to the table are built
5、After judging that it is not empty, the data is saved 至于errorListThe existence of is used to judge whether its field is in the businessnullbe exceptional among themerrorList.size() == 0返回的是布尔类型数据 为trueindicates that it was uploadedexcelThe table is complete and correct.
导出:
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(HttpServletResponse response) {
try {
ExportParams exportParams = new ExportParams("标题:Indicate the intent");
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, governmentsModel.class, new ArrayList<>());
String filename = "信息模板.xls";
response.setContentType("application/force-download");
response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(filename, "UTF-8"));
OutputStream ouputStream = response.getOutputStream();
workbook.write(ouputStream);
ouputStream.flush();
ouputStream.close();
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException(BizExceptionEnum.EXCEL_LOAD_WRONG);
}
}
}
边栏推荐
- "Digital Economy Panorama White Paper" Financial Digital User Chapter released!
- CAS: 178744-28-0, mPEG-DSPE, DSPE-mPEG, methoxy-polyethylene glycol-phosphatidylethanolamine supply
- Fluorescein-PEG-CLS, cholesterol-polyethylene glycol-fluorescein scientific research reagent
- Minimized installation of debian11
- 用栈实现队列
- ML's yellowbrick: A case of interpretability (threshold map) for LoR logistic regression model using yellowbrick based on whether Titanic was rescued or not based on the two-class prediction dataset
- 图论-虚拟节点分层建图
- 《数字经济全景白皮书》金融数字用户篇 重磅发布!
- 举一个 web worker 的例子
- 藏宝计划TreasureProject(TPC)系统模式开发技术原理
猜你喜欢

Network basic learning series four (network layer, data link layer and some other important protocols or technologies)

Pytest学习-setup/teardown

MiniAPI of .NET6 (14): Cross-domain CORS (Part 1)

HCIP BGP lab report

CAS:178744-28-0,mPEG-DSPE,DSPE-mPEG,甲氧基-聚乙二醇-磷脂酰乙醇胺供应

栈的压入、弹出序列

Code Casual Recording Notes_Dynamic Programming_416 Segmentation and Subsetting

RSS订阅微信公众号初探-feed43

HCIP BGP实验报告

Creo 9.0创建几何点
随机推荐
Fluorescein-PEG-CLS, cholesterol-polyethylene glycol-fluorescein scientific research reagent
射频芯片(RFIC)的协议之5G及其调制
ML's yellowbrick: A case of interpretability (threshold map) for LoR logistic regression model using yellowbrick based on whether Titanic was rescued or not based on the two-class prediction dataset
Creo 9.0创建几何点
Zilliz 2023 秋季校园招聘正式启动!
Storage engine written by golang, based on b+ tree, mmap
如何创建一个Web项目
2022/8/3 Exam Summary
栈的压入、弹出序列
射频芯片ATE测试从入门到放弃之参数测试
【深度学习】基于tensorflow的服装图像分类训练(数据集:Fashion-MNIST)
ts用法大全
Kotlin - extension functions and operator overloading
RSS订阅微信公众号初探-feed43
云平台建设解决方案
直播系统聊天技术(八):vivo直播系统中IM消息模块的架构实践
P1996 约瑟夫问题
什么是memoization,它有什么用?
navicat 连接 mongodb 报错[13][Unauthorized] command listDatabases requires authentication
Redis persistence method