SpringBoot基於EasyExcel解析Excel實現文件導出導入、讀取寫入


1. 簡介

  Java解析、生成Excel比較有名的框架有Apache poi、jxl。但他們都存在一個嚴重的問題就是非常的耗內存,poi有一套SAX模式的API可以一定程度的解決一些內存溢出的問題,但POI還是有一些缺陷,比如07版Excel解壓縮以及解壓后存儲都是在內存中完成的,內存消耗依然很大。easyexcel重寫了poi對07版Excel的解析,能夠原本一個3M的excel用POI sax依然需要100M左右內存降低到幾M,並且再大的excel不會出現內存溢出,03版依賴POI的sax模式,在上層做了模型轉換的封裝,讓使用者更加簡單方便。
  64M內存1分鍾內讀取75M(46W行25列)的Excel:

  更多請參考:https://github.com/alibaba/easyexcel

2. 示例代碼

  • 創建工程
  • 修改pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.c3stones</groupId>
	<artifactId>spring-boot-easyexcel-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-boot-easyexcel-demo</name>
	<description>SpringBoot + Easyexcel Demo</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.8.RELEASE</version>
		<relativePath />
	</parent>

	<dependencies>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>easyexcel</artifactId>
			<version>2.2.6</version>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>

</project>
  • 創建實體
import java.util.Date;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 學生實體
 * 
 * @author CL
 *
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@HeadRowHeight(20)
@ColumnWidth(20)
@ContentRowHeight(15)
public class Student {

	@ExcelProperty(index = 0, value = "學號")
	private String sno;

	@ExcelProperty(index = 1, value = "姓名")
	private String name;

	@ExcelProperty(index = 2, value = "年齡")
	private Integer age;

	@ExcelProperty(index = 3, value = "性別")
	private String gender;

	@ExcelProperty(index = 4, value = "籍貫")
	private String nativePlace;

	@ExcelProperty(index = 5, value = "入學時間")
	private Date enrollmentTime;

}
  • 創建文件讀取類
      該類需要繼承抽象類AnalysisEventListener,但是不需要被Spring管理。
import java.util.ArrayList;
import java.util.List;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.c3stones.entity.Student;

import lombok.Getter;

/**
 * 學生讀取類
 * 
 * @author CL
 *
 */
public class StudentListener extends AnalysisEventListener<Student> {

	@Getter
	private List<Student> studentList = new ArrayList<Student>();

	public StudentListener() {
		super();
		studentList.clear();
	}

	/**
	 * 每一條數據解析都會調用
	 */
	@Override
	public void invoke(Student student, AnalysisContext context) {
		studentList.add(student);
	}

	/**
	 * 所有數據解析完成都會調用
	 */
	@Override
	public void doAfterAllAnalysed(AnalysisContext context) {
		studentList.forEach(System.out::println);
	}

}
  • 創建文件導出導入Controller示例
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;
import com.c3stones.entity.Student;
import com.c3stones.listener.StudentListener;

/**
 * 學生Controller
 * 
 * @author CL
 *
 */
@RestController
@RequestMapping(value = "student")
public class StudentController {

	/**
	 * 導出學生信息
	 * 
	 * @param response
	 * @param request
	 * @throws IOException
	 * @throws ParseException
	 */
	@SuppressWarnings("serial")
	@RequestMapping(value = "export")
	public void exportStudentInfos(HttpServletResponse response, HttpServletRequest request)
			throws IOException, ParseException {
		// 設置響應類型
		response.setContentType("application/vnd.ms-excel");
		// 設置字符編碼
		response.setCharacterEncoding("utf-8");
		// 設置響應頭信息
		response.setHeader("Content-disposition",
				"attachment;filename*=utf-8''" + URLEncoder.encode("學生花名冊", "UTF-8") + ".xlsx");

		List<Student> studentList = new ArrayList<Student>() {
			{
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				add(new Student("1001", "張三", 23, "男", "陝西西安", dateFormat.parse("2020-09-01")));
				add(new Student("1002", "李四", 22, "女", "陝西渭南", dateFormat.parse("2020-09-01")));
			}
		};

		// 寫入文件
		EasyExcel.write(response.getOutputStream(), Student.class).sheet("學生信息").doWrite(studentList);
	}

	/**
	 * 導入學生信息
	 * 
	 * @param file
	 * @throws IOException
	 */
	@RequestMapping(value = "import")
	public List<Student> importStudentInfos(MultipartFile file) throws IOException {
		StudentListener studentListener = new StudentListener();
		EasyExcel.read(file.getInputStream(), Student.class, studentListener).sheet().doRead();
		return studentListener.getStudentList();
	}

}
  • 創建文件讀取寫入Controller示例
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.EasyExcel;
import com.c3stones.entity.Student;
import com.c3stones.listener.StudentListener;

/**
 * 文件Controller
 * 
 * @author CL
 *
 */
@RestController
@RequestMapping(value = "file")
public class FileController {

	/**
	 * 讀取Excel
	 * 
	 * @return
	 */
	@RequestMapping(value = "readExcel")
	public List<Student> readExcel() {
		String fileName = "C:\\Users\\Administrator\\Desktop\\學生花名冊.xlsx";
		StudentListener studentListener = new StudentListener();
		EasyExcel.read(fileName, Student.class, studentListener).sheet().doRead();
		return studentListener.getStudentList();
	}

	/**
	 * 寫入Excel
	 * 
	 * @return
	 * @throws ParseException
	 */
	@SuppressWarnings("serial")
	@RequestMapping(value = "writeExcel")
	public Boolean writeExcel() throws ParseException {
		String fileName = "C:\\Users\\Administrator\\Desktop\\學生花名冊2.xlsx";

		List<Student> studentList = new ArrayList<Student>() {
			{
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				add(new Student("2001", "張三2", 23, "男", "陝西西安", dateFormat.parse("2020-09-01")));
				add(new Student("2002", "李四2", 22, "女", "陝西渭南", dateFormat.parse("2020-09-01")));
			}
		};

		EasyExcel.write(fileName, Student.class).sheet("學生信息2").doWrite(studentList);
		return true;
	}

}
  • 創建啟動類
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * 啟動類
 * 
 * @author CL
 *
 */
@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}
  • 啟動項目

3. 測試

  通過Postman依次測試導出、導入、讀取和寫入:

  • 測試導出

      將導出文件保存到桌面(學生花名冊.xlsx)。
  • 測試導入
  • 測試讀取
  • 測試寫入

      可以看到在代碼中配置的文件目錄已存在寫入成功的文件(學生花名冊2.xlsx)。

4. 項目地址

  spring-boot-easyexcel-demo


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM