java -springboot 操作 excel文檔 easyexcel庫 (上傳,下載,導出)


 2、java操作 excel

https://blog.csdn.net/lzp492782442/article/details/106860383/

The supplied data appears to be in the Office 2007+ XML

https://blog.csdn.net/you23hai45/article/details/70196897

關鍵問題的原因還是excel2003和excel2007版本的問題
3、解決辦法

(1)判斷文件后綴名是xls,還是xlsx

(2)如果是xls,使用HSSFWorkbook;如果是xlsx,使用XSSFWorkbook

 

 

 

 

 

項目集成

使用idea開發工具簡單創建了一個easyexcel-demo項目,加入了web模塊以及easyexcel maven依賴,依賴如下:

<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.2.4</version>
</dependency>

 

創建模版 放到 excelTemplate目錄下

 

 

 

 

定義模型映射對象 UserExcelModel

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;


@NoArgsConstructor
@AllArgsConstructor
@Data
public class UserExcelModel  extends BaseRowModel implements Serializable {

    @ExcelProperty(value = "用戶名", index = 0)
    private String name;

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

    @ExcelProperty(value = "手機號", index = 2)
    private String mobile;

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

  

監聽類 

package com.control;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ModelExcelListener extends AnalysisEventListener {
    private List<Object> datas = new ArrayList<>();
    /**
     * 通過 AnalysisContext 對象還可以獲取當前 sheet,當前行等數據
     */
    @Override
    public void invoke(Object data, AnalysisContext context) {
        //數據存儲到list,供批量處理,或后續自己業務邏輯處理。
        log.info("讀取到數據{}",data);
        datas.add(data);
        //根據業務自行處理,可以寫入數據庫等等
    }

    //所以的數據解析完了調用
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有數據解析完成");
    }
}

  

控制層

其中 HttpServletResponse response 如果這個導出excel的方法封裝成方法被調用,那么control的方法也要傳HttpServletResponse response過來------踩坑!!!!

    /**
     * 下載模板
     */
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws Exception {
        ClassPathResource classPathResource = new ClassPathResource("excelTemplate/easyexcel.xlsx");
        InputStream inputStream = classPathResource.getInputStream();
        Workbook workbook = new XSSFWorkbook(inputStream);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("easyexcel2222.xlsx", "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "content-Disposition");
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 導出數據
     */
    @GetMapping("/exportData")
    public void exportData(HttpServletResponse response) throws Exception {

        XSSFWorkbook workbook = new XSSFWorkbook();

//        設置列名
        String[] columnNames = {"用戶名", "年齡", "手機號", "性別"};

//     設置tab
        Sheet sheet1 = workbook.createSheet("第一個tab");
        Sheet sheet = workbook.createSheet("第二個tab");

        //設置字體樣式
        Font titleFont = workbook.createFont();
        titleFont.setFontName("simsun");
        titleFont.setBold(true);
        titleFont.setColor(IndexedColors.BLACK.index);
        XSSFCellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
        titleStyle.setFont(titleFont);

//        操作第x行開始
        Row titleRow = sheet.createRow(0);

        for (int i = 0; i < columnNames.length; i++) {
//            寫入幾行第幾列
            Cell cell = titleRow.createCell(i);
//            寫入的內容
            cell.setCellValue(columnNames[i]);
//            寫入的格式
            cell.setCellStyle(titleStyle);
        }

        //模擬構造數據
        List<UserExcelModel> dataList = new ArrayList<>();
        dataList.add(new UserExcelModel("張三", 12, "13867098765", "男"));
        dataList.add(new UserExcelModel("張三1", 12, "13867098765", "男"));
        dataList.add(new UserExcelModel("張三2", 12, "13867098765", "男"));
        dataList.add(new UserExcelModel("張三3", 12, "13867098765", "男"));

        //創建數據行並寫入值
        for (int j = 0; j < dataList.size(); j++) {
            UserExcelModel userExcelModel = dataList.get(j);
//            獲取tab表里面有多少行數據
            int lastRowNum = sheet.getLastRowNum();

//            指定寫入的行
            Row dataRow = sheet.createRow(lastRowNum + 1);
//            指定第寫入第幾列
            dataRow.createCell(0).setCellValue(userExcelModel.getName());
            dataRow.createCell(1).setCellValue(userExcelModel.getAge());
            dataRow.createCell(2).setCellValue(userExcelModel.getMobile());
            dataRow.createCell(3).setCellValue(userExcelModel.getSex());
        }
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("easyexcel4444.xls", "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "content-Disposition");
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }

//    上傳
    @PostMapping("/readExcel")
    public List<UserExcelModel> readExcel(@RequestParam("file") MultipartFile file){
        List<UserExcelModel> list = new ArrayList<>();
        try {
            list = EasyExcel.read(file.getInputStream(),UserExcelModel.class,new ModelExcelListener()).sheet().doReadSync();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }    /**
     * 下載模板
     */
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws Exception {
        ClassPathResource classPathResource = new ClassPathResource("excelTemplate/easyexcel.xlsx");
        InputStream inputStream = classPathResource.getInputStream();
        Workbook workbook = new XSSFWorkbook(inputStream);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("easyexcel2222.xlsx", "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "content-Disposition");
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 導出數據
     */
    @GetMapping("/exportData")
    public void exportData(HttpServletResponse response) throws Exception {

        XSSFWorkbook workbook = new XSSFWorkbook();

//        設置列名
        String[] columnNames = {"用戶名", "年齡", "手機號", "性別"};

//     設置tab
        Sheet sheet1 = workbook.createSheet("第一個tab");
        Sheet sheet = workbook.createSheet("第二個tab");

        //設置字體樣式
        Font titleFont = workbook.createFont();
        titleFont.setFontName("simsun");
        titleFont.setBold(true);
        titleFont.setColor(IndexedColors.BLACK.index);
        XSSFCellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
        titleStyle.setFont(titleFont);

//        操作第x行開始
        Row titleRow = sheet.createRow(0);

        for (int i = 0; i < columnNames.length; i++) {
//            寫入幾行第幾列
            Cell cell = titleRow.createCell(i);
//            寫入的內容
            cell.setCellValue(columnNames[i]);
//            寫入的格式
            cell.setCellStyle(titleStyle);
        }

        //模擬構造數據
        List<UserExcelModel> dataList = new ArrayList<>();
        dataList.add(new UserExcelModel("張三", 12, "13867098765", "男"));
        dataList.add(new UserExcelModel("張三1", 12, "13867098765", "男"));
        dataList.add(new UserExcelModel("張三2", 12, "13867098765", "男"));
        dataList.add(new UserExcelModel("張三3", 12, "13867098765", "男"));

        //創建數據行並寫入值
        for (int j = 0; j < dataList.size(); j++) {
            UserExcelModel userExcelModel = dataList.get(j);
//            獲取tab表里面有多少行數據
            int lastRowNum = sheet.getLastRowNum();

//            指定寫入的行
            Row dataRow = sheet.createRow(lastRowNum + 1);
//            指定第寫入第幾列
            dataRow.createCell(0).setCellValue(userExcelModel.getName());
            dataRow.createCell(1).setCellValue(userExcelModel.getAge());
            dataRow.createCell(2).setCellValue(userExcelModel.getMobile());
            dataRow.createCell(3).setCellValue(userExcelModel.getSex());
        }
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("easyexcel4444.xls", "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "content-Disposition");
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }

//    上傳
    @PostMapping("/readExcel")
    public List<UserExcelModel> readExcel(@RequestParam("file") MultipartFile file){
        List<UserExcelModel> list = new ArrayList<>();
        try {
            list = EasyExcel.read(file.getInputStream(),UserExcelModel.class,new ModelExcelListener()).sheet().doReadSync();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

  

 

 

本地操作記錄

 

ModelExcelListener.java  (做了一下修改,讓他展示成json)
package com.control;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSONArray;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Data
public class ModelExcelListener extends AnalysisEventListener {
    private List<Object> datas = new ArrayList<>();
    /**
     * 通過 AnalysisContext 對象還可以獲取當前 sheet,當前行等數據
     */
    @Override
    public void invoke(Object data, AnalysisContext context) {
        //數據存儲到list,供批量處理,或后續自己業務邏輯處理。
//        log.info("讀取到數據{}",data);
        String data2= JSONArray.toJSONString(data);
        datas.add(data2);
        log.info("讀取到數據1111{}",datas);
        //根據業務自行處理,可以寫入數據庫等等
    }

    //所以的數據解析完了調用
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有數據解析完成");
    }
}

 

其他的和上面的一致

控制層

讀取本地的數據

//    數據讀取
    @GetMapping("/excel")
    public void excel(){
        String fileName ="/Users/lucax/Desktop/工作/小工具腳本/B端測試平台/代碼存檔/easyexcel.xlsx";
        // 這里 需要指定讀用哪個class去讀,然后讀取第一個sheet 文件流會自動關閉
        ModelExcelListener ModelExcelListener=new ModelExcelListener();
        EasyExcel.read(fileName, UserExcelModel.class, ModelExcelListener).sheet(0).doRead();
//      這里就拿到excel的數據了
        List aa=ModelExcelListener.getDatas();
        log.info(String.valueOf(aa));
    }

 

 

官網操作 https://www.yuque.com/easyexcel/doc/easyexcel

 

 

前端vue下載記錄:  https://www.cnblogs.com/kaibindirver/p/15797386.html 

有空試試,可能在后端加上 responseType: 'arraybuffer' 的話前端估計久不用加,也能導出


免責聲明!

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



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