퐁
springboot 프로젝트에 필요한 장면 스타터(스타터) 외에도 pom은 다음 종속성 esaypoi를 추가해야 합니다.
이전에 사용하던 3.2.0 블로거인 easypoi의 버전에 주의하여 시작할 때 항상 오류를 보고하고 프로젝트를 다시 빌드하고 낮은 버전으로 교체하여 성공적으로 실행했습니다.
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.0.1</version>
</dependency>
제어 장치
@GetMapping("/export")
public void export(HttpServletResponse response){
//模拟从数据库获取需要导出的数据
List<Person> personList = new ArrayList<>();
Person person1 = new Person("柱间","1",new Date());
Person person2 = new Person("小南","2", new Date());
Person person3 = new Person("鼬","1", new Date());
Person person4 = new Person("萨斯给","1",new Date());
personList.add(person1);
personList.add(person2);
personList.add(person3);
personList.add(person4);
//导出操作
ExcelUtil.exportExcel(personList,"报名表","忍者",Person.class,"火影.xls",response);
}
@PostMapping("/importExcel")
public void importExcel(MultipartFile file){
String filePath = "D:\\火影.xls";
//解析excel,
// 方式一:根据文件路径解析
// List<Person> personList = ExcelUtil.importExcel(filePath,1,1,Person.class);
// 方式二:也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)导入
List<Person> personList = ExcelUtil.importExcel(file, 1, 1, Person.class);
System.out.println("导入数据一共【"+personList.size()+"】行");
//TODO 保存数据库
System.out.println(personList);
}
콩
public class Person {
@Excel(name = "姓名", orderNum = "0")
private String name;
@Excel(name = "性别", replace = {
"男_1", "女_2"}, orderNum = "1")
private String sex;
@Excel(name = "生日", exportFormat = "yyyy-MM-dd", orderNum = "2")
private Date birthday;
public Person() {
}
getter setter略...
도구
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
public class ExcelUtil {
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response){
ExportParams exportParams = new ExportParams(title, sheetName);
exportParams.setCreateHeadRows(isCreateHeader);
defaultExport(list, pojoClass, fileName, response, exportParams);
}
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
}
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
defaultExport(list, fileName, response);
}
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
if (workbook != null);
downLoadExcel(fileName, response, workbook);
}
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
workbook.write(response.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
if (workbook != null);
downLoadExcel(fileName, response, workbook);
}
public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
if (StringUtils.isBlank(filePath)){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
}catch (NoSuchElementException e){
throw new RuntimeException("模板不能为空");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
return list;
}
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
if (file == null){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
}catch (NoSuchElementException e){
throw new RuntimeException("excel文件不能为空");
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return list;
}
}
프런트 엔드 코드
<div id="center">
<form method="post" action="/importExcel" enctype="multipart/form-data">
上传Excel: <input type="file" name="file"/>
<br />
<button>上传</button>
</form>
<br />
<a href="/export">下载</a>
</div>
시험
다운로드
업로드
콘솔 인쇄 정보
요약하다
easypoi를 사용하면 Excel 파일의 업로드, 다운로드 및 구문 분석 작업을 쉽게 실현할 수 있습니다. 위의 코드는 단순한 데모일 뿐입니다. 특정 비즈니스 시나리오에서는 일부 보안 확인 작업을 추가해야 하고 업로드된 파일은 그에 따라 구문 분석해야 합니다. 그런 다음 데이터가 데이터베이스에 저장됩니다.