Java+EasyExcel實作檔案匯入匯出
引言
專案中需要Excel檔案的匯入與匯出Excel并下載,例如,匯入員工資訊,匯出員工資訊,手動輸入比較繁瑣,所以本篇博文教大家如何在Java中匯入Excel檔案與匯出Excel檔案
技術堆疊
Excel工具:EasyExcel
選用框架:Spring、Spring MVC、MyBatis(SSM)
專案構建管理工具:Maven
需求:
- 要求利用excel工具實作員工資訊的匯入與匯出
- 匯出要求為輸出到指定位置并下載
- 匯入檔案匯入后,存入資料庫,并顯示在頁面
- 匯出檔案,點擊匯出后寫入指定地址,并下載該檔案
效果圖

專案結構

核心原始碼
匯入阿里巴巴EasyExcel依賴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.6</version>
</dependency>
這里采用EasyExcel,為什么不采用POI呢?
因為EasyExcel是對POI做的一個升級,POI相對于笨重,EasyExcel去除了一些POI比較繁瑣的東西,所以EasyExcel比較輕量級,所以本文采用EasyExcel
EasyExcel是阿里巴巴的產品,POI是Apache基金會的開源產品,EasyExcel對POI做了一個升級
核心物體類
package com.wanshi.spring.entity;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
@ExcelIgnore
private String noid;
@ColumnWidth(20)
@ExcelProperty("員工姓名")
private String emp_name;
@ColumnWidth(20)
@ExcelProperty("員工年齡")
private Integer emp_age;
@ExcelIgnore
private Integer emp_sex;
//冗余欄位
@ColumnWidth(20)
@ExcelProperty("員工性別")
private String str_emp_sex;
@ColumnWidth(20)
@ExcelProperty("員工工資")
private Double emp_salary;
@ColumnWidth(20)
@ExcelProperty("員工住址")
private String emp_address;
@ColumnWidth(20)
@ExcelProperty("員工崗位")
private String emp_position;
//分頁相關,當前頁與每頁的資料條數
@ExcelIgnore
private Integer pageNum;
@ExcelIgnore
private Integer pageSize;
}
核心監聽器類
EmployeeListener類:
package com.wanshi.spring.listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.wanshi.spring.entity.Employee;
import java.util.ArrayList;
import java.util.List;
public class EmployeeReadListener extends AnalysisEventListener<Employee> {
//員工集合
private static List<Employee> employeeList = new ArrayList<>();
// 每讀一樣,會呼叫該invoke方法一次
@Override
public void invoke(Employee data, AnalysisContext context) {
employeeList.add(data);
System.out.println("決議到一條資料:" + data);
}
// 全部讀完之后,會呼叫該方法
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
System.out.println("全部決議完成");
}
/**
* 回傳讀取到的員工集合
* @return
*/
public static List<Employee> getStudentList() {
return employeeList;
}
}
EasyExcel匯入檔案
Test測驗類實作檔案匯入并存入資料庫
@Test
public void test1(){
ExcelReaderBuilder workBook = EasyExcel.read
("C:\\Users\\投訓稱\\Desktop\\員工.xlsx", Employee.class, new EmployeeReadListener());
// 封裝作業表
ExcelReaderSheetBuilder sheet1 = workBook.sheet();
// 讀取
sheet1.doRead();
//寫入資料庫
List<Employee> studentList = EmployeeReadListener.getStudentList();
for (Employee employee : studentList) {
employee.setNoid(PbSecretUtils.uuid());
employeeMapper.insert(employee);
}
}
通過頁面點擊匯入檔案并存入資料庫
EmployeeController類:
@PostMapping("/import_employee_excel")
public String importEmployeeExcel(MultipartFile emp_excel) {
employeeService.importExcel(emp_excel);
return "redirect:/employee/list";
}
EmployeeService類:
/**
* 獲取用戶選擇的檔案并將檔案存入指定位置再將資料存入資料庫
* @param emp_excel
* @return
*/
public Integer importExcel(MultipartFile emp_excel) {
try {
String fileName = FileUploadUtil.upload(emp_excel, "");
ExcelReaderBuilder workBook = EasyExcel.read
(GlobalSet.upload_url+fileName, Employee.class, new EmployeeReadListener());
// 封裝作業表
ExcelReaderSheetBuilder sheet1 = workBook.sheet();
// 讀取
sheet1.doRead();
List<Employee> studentList = EmployeeReadListener.getStudentList();
for (Employee employee : studentList) {
employee.setNoid(PbSecretUtils.uuid());
if ("男".equals(employee.getStr_emp_sex())) {
employee.setEmp_sex(1);
} else {
employee.setEmp_sex(2);
}
employeeMapper.insert(employee);
}
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
EasyExcel匯出檔案
Test測驗類匯出檔案到指定檔案
@Test
public void test2() throws FileNotFoundException {
List<Employee> employeeList = initData();
ExcelWriterBuilder workBook = EasyExcel.write(GlobalSet.download_url, Employee.class);
// sheet方法引數: 作業表的順序號(從0開始)或者作業表的名字
workBook.sheet("測驗資料表").doWrite(employeeList);
System.out.println("寫入完成!");
}
/**
* 生成測驗資料
* @return
*/
public List<Employee> initData() {
List<Employee> employeeList = new ArrayList<>();
for (int i = 1; i < 100; i++) {
Employee employee = new Employee();
employee.setEmp_name("小王說:"+i);
employee.setEmp_age(19);
if (i % 10 == 0) {
employee.setEmp_sex(1);
} else {
employee.setEmp_sex(2);
}
employee.setEmp_salary(19999.00+i);
employee.setEmp_address("北京市朝陽區"+i);
employee.setEmp_position("Java高級工程師");
employeeList.add(employee);
}
return employeeList;
}
通過頁面匯出到指定檔案后并下載檔案
EmployeeController類
@GetMapping("/export_employee_excel")
public void exportEmployeeExcel(HttpServletResponse response) {
try {
employeeService.exportEmployeeExcel(response);
} catch (IOException e) {
e.printStackTrace();
}
}
EmployeeService類:
public void exportEmployeeExcel(HttpServletResponse response) throws IOException {
List<Employee> kspwStudentSeatList = list();
try {
ExcelWriterBuilder workBook = EasyExcel.write(GlobalSet.download_url, Employee.class);
// sheet方法引數: 作業表的順序號(從0開始)或者作業表的名字
workBook.sheet("員工資訊").doWrite(kspwStudentSeatList);
downloadTempalate(response);
System.out.println("寫入完成!");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 下載檔案
* @param response
* @throws IOException
*/
public static void downloadTempalate(HttpServletResponse response) throws IOException {
// 告訴瀏覽器用什么軟體可以打開此檔案
response.setHeader("content-Type", "application/vnd.ms-excel");
// 下載檔案的默認名稱
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("員工資訊.xlsx", "utf-8"));
//4. 創建輸入、輸出流
FileInputStream input = new FileInputStream(GlobalSet.download_url);
ServletOutputStream sos = response.getOutputStream();
//IO流獲取檔案的位元組流,然后再回應給瀏覽器
byte[] arr = new byte[1024];
int res = 0;
while((res = input.read(arr)) > 0){
//將讀取的內容輸出到輸出流中
sos.write(arr, 0, res);
}
input.close();
sos.close();
}
結語
至此,資料完美匯入匯出,該案例通俗易懂,詳細一步步帶入,通過本案例,可實作檔案基本的匯入匯出,認真學習的你很耀眼,相信你的技術一定會有一個質的飛躍,好啦,本周技術分享到此結束
都看到這里啦,確定不點贊嘛
若在本專案中遇到技術難題,可在下方評論區留言或私信我,授人以魚不如授人以漁
百度網盤地址:鏈接: https://pan.baidu.com/s/1vmrL7vl5Hlq-SqjdndOKyQ 提取碼: me3n
如果你覺得博主寫的不錯的話,不妨給個一鍵三連,點擊下方小拳頭即可一鍵三連,
感謝你的支持!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/386560.html
標籤:java
