使用Java和EasyExcel輕鬆實現檔案匯入匯出

相關標籤:1.瞭解Java中的記憶體回收
2. Java Map的巧妙設計

Java與EasyExcel簡介:

專案需要匯入和匯出Excel檔案並下載。手動輸入員工資訊既繁瑣又容易出錯,因此本篇部落格將教你如何在Java中實現Excel檔案的匯入和匯出。

技術棧
Excel工具:EasyExcel
選用架構:Spring、Spring MVC、MyBatis(SSM)
專案構建管理工具:Maven
需求:

1.使用Excel工具實現員工資訊的匯入和匯出
2.匯出要求輸出到指定位置並下載
3.匯入檔案後儲存到資料庫並在頁面上展示
4.匯出檔案時,點擊匯出寫入指定地址並下載

Java與EasyExcel效果圖

專案結構

核心原始碼

引入阿里巴巴EasyExcel依賴
< dependency >
< groupId > com.alibaba
< artifactId > easyexcel
< version > 2.1.6

這裡使用EasyExcel,為什麼不用POI?
因為EasyExcel是POI的升級版,POI相對臃腫,EasyExcel去除了POI中一些繁瑣的部分,因此更加輕量,所以本文使用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 ( " Employee Name" )
private String emp_name ;

@ColumnWidth ( 20 ) _
@ExcelProperty ( " Employee Age" )
private Integer emp_age ;

@ExcelIgnore _
private Integer emp_sex ;

// redundant fields
@ColumnWidth ( 20 ) _
@ExcelProperty ( " employee gender" )
private String str_emp_sex ;

@ColumnWidth ( 20 ) _
@ExcelProperty ( "Employee Salary " )
private Double emp_salary ;

@ColumnWidth ( 20 ) _
@ExcelProperty ( " Employee Address" )
private String emp_address ;

@ColumnWidth ( 20 ) _
@ExcelProperty ( "EmployeePosition " )
private String emp_position ;

/ / Paging related, the current page and the number of data per page
@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 > {

// employee collection
private static List employeeList = new ArrayList < >( );

// Each time the read is the same, the invoke method will be called once
@Override
public void invoke ( Employee data, AnalysisContext context) {
employeeList.add (data);
System.out.println ( "Parse to a piece of data: " + data);
}

// After reading all, this method will be called
@Override
public void doAfterAllAnalysed ( AnalysisContext context) {
System.out.println ( "All parsing completed" );
}

/**
* Return the read employee collection
* @return
*/
public static List getStudentList ( ) {
return employeeList ;
}
}

Java+EasyExcel 匯入檔案



Java+EasyExcel,測試類別實現檔案匯入並儲存到資料庫

@Test
public void test1 () {
ExcelReaderBuilder workBook = EasyExcel.read
( "C:\Users\wanghuicall\Desktop\employee.xlsx" , Employee . class , new EmployeeReadListener ()) ;

// 封裝工作表
ExcelReaderSheetBuilder sheet1 = workBook.sheet ();
// 讀取
sheet1.doRead();

//寫入資料庫
List 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 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 ;
}

Java+EasyExcel 匯出檔案



測試類別匯出檔案到指定位置

@Test
public void test2 () throws FileNotFoundException {

List employeeList = initData ( );


ExcelWriterBuilder workBook = EasyExcel.write ( GlobalSet.download_url , Employee . class ) ;

// sheet方法參數:工作表的序號(從0開始)或工作表的名稱
workBook.sheet ( "Test Data Sheet" ). doWrite ( employeeList );
System.out.println ( "Write complete!" );
}

/**
* 產生測試資料
* @return
*/
public List initData ( ) {
List 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 ( "Beijing Chaoyang District" + i );
employee.setEmp_position ( "Java Senior Engineer" );
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 kspwStudentSeatList = list();
try {
ExcelWriterBuilder workBook = EasyExcel.write(GlobalSet.download_url, Employee.class);
// sheet方法參數:工作表的序號(從0開始)或工作表的名稱
workBook.sheet ( "Employee Information" ). doWrite ( kspwStudentSeatList );
downloadTempalate (response);
System.out.println ( "Write complete!" );
} 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 ( "Employee Information.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 ();
}

相關文章

探索更多特惠

  1. 簡訊服務(SMS)與Direct Mail

    5萬封郵件包低至1.99美元,120條簡訊僅需1.00美元

phone 聯絡我們
Hi, I'm Alibaba Cloud AI Assistant!
I can help with questions and solutions.