Ali EasyExcel use to read and write Excel files

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Allen_jinjie/article/details/102687886

First introduced pom.xml dependent, EasyExcel version update fast, different versions of the API are different, some have been abandoned.

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>easyexcel</artifactId>
	<version>2.0.0</version>
</dependency>

Excel package height EasyExcel operation, the following is a read Excel, comprising a header, contents of the line:

public void importSynonyms(MultipartFile file, String type) throws Exception {
	ExcelListener<SynonymModel> listener = new ExcelListener<>();
	try {
		EasyExcelFactory.read(file.getInputStream(), SynonymModel.class, listener).sheet(0).doRead();
	} catch (Exception e) {
		logger.info(e.getMessage());
	}
	List<SynonymModel> rows = listener.getRows();
	...
    // 完成 Excel到映射类对象的反射,可以进行业务逻辑处理了
}

In order to successfully resolve EasyExcel and reflected as java object, need to define a mapping target class, and implements AnalysisEventListener interface that parses each line to Excel, and provide a method and an auxiliary hook events. The following is a mapping class, attention must index 0-based, consistent with the value of the column number and Excel files.

Monitor interface is responsible for parsing Excel, line by line and reflection to resolve the mapping class object.

The following are exporting data EasyExcel:

public void exportConceptMapping(int id, HttpServletResponse resp){
	List<ConceptMappingList> data = new ArrayList<>();
	// 处理 data 数据
	WriteSheet sheet = new WriteSheet();
	WriteTable table = new WriteTable();
	List<List<String>> head = new ArrayList<>();
	List<String> col = new ArrayList<>();
	col.add("列名 1");
	head.add(col);
	List<String> col2 = new ArrayList<>();
	col2.add("列名 2");
	head.add(col2);
	table.setHead(head);
	try {
		try (BufferedOutputStream ops = new BufferedOutputStream(resp.getOutputStream())) {
			resp.setContentType("application/x-xls");
			resp.addHeader("Content-Disposition", "attachment;filename=test.xlsx");
			resp.setCharacterEncoding("UTF-8");
			
			ExcelWriter writer = EasyExcelFactory.write(ops).build();
			writer.write(data, sheet, table);
			writer.finish();
		}
	} catch (IOException e) {
		e.printStackTrace();
		throw new RuntimeException("导出文件出错:" + e.getMessage());
	}
}

 

Guess you like

Origin blog.csdn.net/Allen_jinjie/article/details/102687886