1. 程式人生 > 其它 >easyExcel匯出Excel表格

easyExcel匯出Excel表格

目錄

easyExcel匯出Excel表格

參照簡書:https://www.jianshu.com/p/882db0771b80

官網:https://github.com/alibaba/easyexcel

首先easyExcel能快速、簡單的匯出Excel,避免了OOM(記憶體溢位)的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模式。在上層做了模型轉換的封裝,讓使用者更加簡單方便

使用的依賴

前提是建立一個SpringBoot專案。

<!--easyExcel -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>easyexcel</artifactId>
			<version>1.1.2-beta5</version>
		</dependency>

Controller

@Controller
public class UserController {
	public List<User> getAllUser() {
		List<User> userList = new ArrayList<>();
		for (int i = 0; i < 100; i++) {
			User user = User.builder().name("張三" + i).password("1234").age(i).build();
			userList.add(user);
		}
		return userList;
	}
}

pojo

注意事項,實體類需要繼承BaseRowModel,@Data和@Builder的作用是,@Data為實體類提供get/set方法,toString、構造方法。而@Builder能夠方便批量建立實體類。

@ExcelProperty為Excel設定表頭資訊

@Data
@Builder
public class User extends BaseRowModel{
	@ExcelProperty(value = "學號",index = 0)
	private Integer id;
	@ExcelProperty(value = "姓名",index = 1)
	private String name;
	@ExcelProperty(value = "密碼",index = 2)
	private String password;
	@ExcelProperty(value = "年齡",index = 3)
	private Integer age;
}

Test

讀Excel

DEMO程式碼地址:https://github.com/alibaba/easyexcel/blob/master/src/test/java/com/alibaba/easyexcel/demo/read/ReadTest.java

寫Excel

DEMO程式碼地址:https://github.com/alibaba/easyexcel/blob/master/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java

web上傳、下載

DEMO程式碼地址:https://github.com/alibaba/easyexcel/blob/master/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java

@SpringBootTest
class ExcelDemoApplicationTests {
		// 注入controller類用來呼叫返回list集合的方法
		@Autowired
		private UserController userController;

		@Test
		public void contextLoads() {
			// 檔案輸出位置
			OutputStream out = null;
			try {
				out = new FileOutputStream("d:\\test.xlsx");
				
				ExcelWriter writer = EasyExcelFactory.getWriter(out);

				// 寫僅有一個 Sheet 的 Excel 檔案, 此場景較為通用
				Sheet sheet1 = new Sheet(1, 0,User.class);

				// 第一個 sheet 名稱
				sheet1.setSheetName("第一個sheet");

				// 寫資料到 Writer 上下文中
				// 入參1: 資料庫查詢的資料list集合
				// 入參2: 要寫入的目標 sheet
				writer.write(userController.getAllUser(),sheet1);

				// 將上下文中的最終 outputStream 寫入到指定檔案中
				writer.finish();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				try {
					// 關閉流
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
}