您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)Java+EasyExcel如何實(shí)現(xiàn)文件的導(dǎo)入導(dǎo)出,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
項(xiàng)目中需要Excel文件的導(dǎo)入與導(dǎo)出Excel并下載,例如,導(dǎo)入員工信息,導(dǎo)出員工信息,手動(dòng)輸入比較繁瑣,所以本篇博文教大家如何在Java中導(dǎo)入Excel文件與導(dǎo)出Excel文件
技術(shù)棧
Excel工具:EasyExcel
選用框架:Spring、Spring MVC、MyBatis(SSM)
項(xiàng)目構(gòu)建管理工具:Maven
需求:
1.要求利用excel工具實(shí)現(xiàn)員工信息的導(dǎo)入與導(dǎo)出
2.導(dǎo)出要求為輸出到指定位置并下載
3.導(dǎo)入文件導(dǎo)入后,存入數(shù)據(jù)庫,并顯示在頁面
4.導(dǎo)出文件,點(diǎn)擊導(dǎo)出后寫入指定地址,并下載該文件
導(dǎo)入阿里巴巴EasyExcel依賴
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.1.6</version> </dependency>
這里采用EasyExcel,為什么不采用POI呢?
因?yàn)镋asyExcel是對(duì)POI做的一個(gè)升級(jí),POI相對(duì)于笨重,EasyExcel去除了一些POI比較繁瑣的東西,所以EasyExcel比較輕量級(jí),所以本文采用EasyExcel
EasyExcel是阿里巴巴的產(chǎn)品,POI是Apache基金會(huì)的開源產(chǎn)品,EasyExcel對(duì)POI做了一個(gè)升級(jí)
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; //分頁相關(guān),當(dāng)前頁與每頁的數(shù)據(jù)條數(shù) @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<>(); // 每讀一樣,會(huì)調(diào)用該invoke方法一次 @Override public void invoke(Employee data, AnalysisContext context) { employeeList.add(data); System.out.println("解析到一條數(shù)據(jù):" + data); } // 全部讀完之后,會(huì)調(diào)用該方法 @Override public void doAfterAllAnalysed(AnalysisContext context) { System.out.println("全部解析完成"); } /** * 返回讀取到的員工集合 * @return */ public static List<Employee> getStudentList() { return employeeList; } }
Test測試類實(shí)現(xiàn)文件導(dǎo)入并存入數(shù)據(jù)庫
@Test public void test1(){ ExcelReaderBuilder workBook = EasyExcel.read ("C:\\Users\\王會(huì)稱\\Desktop\\員工.xlsx", Employee.class, new EmployeeReadListener()); // 封裝工作表 ExcelReaderSheetBuilder sheet1 = workBook.sheet(); // 讀取 sheet1.doRead(); //寫入數(shù)據(jù)庫 List<Employee> studentList = EmployeeReadListener.getStudentList(); for (Employee employee : studentList) { employee.setNoid(PbSecretUtils.uuid()); employeeMapper.insert(employee); } }
通過頁面點(diǎn)擊導(dǎo)入文件并存入數(shù)據(jù)庫
EmployeeController類:
@PostMapping("/import_employee_excel") public String importEmployeeExcel(MultipartFile emp_excel) { employeeService.importExcel(emp_excel); return "redirect:/employee/list"; }
EmployeeService類:
/** * 獲取用戶選擇的文件并將文件存入指定位置再將數(shù)據(jù)存入數(shù)據(jù)庫 * @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; }
Test測試類導(dǎo)出文件到指定文件
@Test public void test2() throws FileNotFoundException { List<Employee> employeeList = initData(); ExcelWriterBuilder workBook = EasyExcel.write(GlobalSet.download_url, Employee.class); // sheet方法參數(shù): 工作表的順序號(hào)(從0開始)或者工作表的名字 workBook.sheet("測試數(shù)據(jù)表").doWrite(employeeList); System.out.println("寫入完成!"); } /** * 生成測試數(shù)據(jù) * @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("北京市朝陽區(qū)"+i); employee.setEmp_position("Java高級(jí)工程師"); employeeList.add(employee); } return employeeList; }
通過頁面導(dǎo)出到指定文件后并下載文件
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方法參數(shù): 工作表的順序號(hào)(從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"); // 下載文件的默認(rèn)名稱 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("員工信息.xlsx", "utf-8")); //4. 創(chuàng)建輸入、輸出流 FileInputStream input = new FileInputStream(GlobalSet.download_url); ServletOutputStream sos = response.getOutputStream(); //IO流獲取文件的字節(jié)流,然后再響應(yīng)給瀏覽器 byte[] arr = new byte[1024]; int res = 0; while((res = input.read(arr)) > 0){ //將讀取的內(nèi)容輸出到輸出流中 sos.write(arr, 0, res); } input.close(); sos.close(); }
關(guān)于“Java+EasyExcel如何實(shí)現(xiàn)文件的導(dǎo)入導(dǎo)出”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。