easyExcel 的web用法

easyExcel的web用法

項目工程代碼 https://github.com/woyaochengweidaniu/javaEE/tree/master/file-handling

依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>easyexcel</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>easyexcel</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>1.1.2-beat1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.5.16</version>
        </dependency>

        <dependency>
            <groupId>com.battcn</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>2.1.5-RELEASE</version>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

建立實體類

@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
public class User extends BaseEntity {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id",type = IdType.AUTO)
    private Integer id;

    private String userName;

    private Integer age;

    private String sex;

    private String address;

    private String phone;

    private String hobby;

    private Date birthday;

    private LocalDateTime createTime;


}

mapper ,service,controller 使用mybatisplus自動生成

建立 導入module

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

import java.util.Date;

/**
 * @author lcm
 */
@Data
public class UserReadModule extends BaseRowModel {

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

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

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

    @ExcelProperty(value = "家庭住址",index = 3)
    private String address;

    @ExcelProperty(value = "手機電話",index = 4)
    private String phone;

    @ExcelProperty(value = "業餘愛好",index = 5)
    private String hobby;

    @ExcelProperty(value = "出生日期",index = 6,format = "yyyy-MM-dd")
    private Date birthday;
}

建立導出module

@Data
public class UserWriteModule extends BaseRowModel {

    private Integer id;

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

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

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

    @ExcelProperty(value = "家庭住址",index = 3)
    private String address;

    @ExcelProperty(value = "手機電話",index = 4)
    private String phone;

    @ExcelProperty(value = "業餘愛好",index = 5)
    private String hobby;

    @ExcelProperty(value = "出生日期",index = 6)
    private LocalDate birthday;
}

建立Excel監聽器 監聽導入的數據 進行數據處理

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.easyexcel.work.dto.UserReadModule;
import com.example.easyexcel.work.entity.User;
import com.example.easyexcel.work.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * 監聽器   監聽Excel導入時會去讀取Excel的內容
 * @author lcm
 */
@Component
public class ExcelListener extends AnalysisEventListener {

    @Autowired
    private IUserService userService;

    private List<UserReadModule> userReadModuleList = new ArrayList<>();

    public ExcelListener(){};
    public ExcelListener(IUserService service){
        this.userService = service;
    }


    /**
     * 該方法是逐條讀取Excel 的內容
     * @param object
     * @param context
     */
    @Override
    public void invoke(Object object, AnalysisContext context) {
        Integer currentRowNum = context.getCurrentRowNum();
        if (currentRowNum!=0){
            System.out.println(object);
            UserReadModule userReadModule = (UserReadModule) object;
            userReadModuleList.add(userReadModule);
        }

    }


    /**
     * 將全部的內容讀取以後的方法
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

        System.out.println("全部數據讀取完畢");
        List<User> list = new ArrayList<>();
        userReadModuleList.forEach(userReadModule -> {
            User user = new User();
            BeanUtils.copyProperties(userReadModule,user);
            list.add(user);
        });

        userService.saveBatch(list);



    }
}

excel工具類

import cn.hutool.core.util.URLUtil;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.poi.util.StringUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ExcelUtils {

    public static void exportModule(String filename, HttpServletResponse response, Class<? extends BaseRowModel> classModule, List<? extends BaseRowModel> data) throws IOException {

        String fileName = new String((filename+ new SimpleDateFormat("yyyyMMdd").format(new Date()))
                .getBytes(), "UTF-8");
        ServletOutputStream out = response.getOutputStream();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename="+ URLUtil.encode(fileName, StringUtil.UTF8) +".xlsx");
        ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
        Sheet sheet = new Sheet(1, 0, classModule, filename, null);
        sheet.setAutoWidth(Boolean.TRUE);
        writer.write(data,sheet);
        writer.finish();
        out.close();

    }

    public static void exportMap(String filename, HttpServletResponse response, List<List<String>> headList, List<? extends BaseRowModel> data) throws IOException {

        String fileName = new String((filename+ new SimpleDateFormat("yyyyMMdd").format(new Date()))
                .getBytes(), "UTF-8");
        ServletOutputStream out = response.getOutputStream();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename="+ URLUtil.encode(fileName, StringUtil.UTF8) +".xlsx");
        ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
        Sheet sheet = new Sheet(1,0);
        sheet.setAutoWidth(Boolean.TRUE);
        sheet.setHead(headList);
        writer.write(data,sheet);
        writer.finish();
        out.close();

    }

}

controller層實現web端操做

package com.example.filehandling.easyexcel.controller;


import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.example.filehandling.easyexcel.dto.UserReadModule;
import com.example.filehandling.easyexcel.dto.UserWriteModule;
import com.example.filehandling.easyexcel.entity.User;
import com.example.filehandling.easyexcel.listener.ExcelListener;
import com.example.filehandling.easyexcel.mapper.UserMapper;
import com.example.filehandling.easyexcel.service.IUserService;
import com.example.filehandling.util.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * 使用阿里巴巴開源項目 easy excel
 * 項目源碼:https://github.com/alibaba/easyexcel
 *
 *
 * @author lcm
 * @since 2019-07-04
 */
@Api(description = "easyExcel 的用法")
@RestController
@RequestMapping("/work/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ExcelListener excelListener;


    @ApiOperation(value = "下載模板")
    @GetMapping("downLoadTemplate")
    public void downLoadTemplate(HttpServletResponse response) throws IOException {
        //第三個參數new ArrayList()  是咱們須要填充的數據 
        ExcelUtils.exportModule("導入模板",response, UserWriteModule.class,new ArrayList<>());
    }


    @ApiOperation("Excel導入")
    @PostMapping("uploadData")
    public Object uploadData(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        EasyExcelFactory.readBySax(inputStream, new Sheet(1, 1, UserReadModule.class), excelListener);
        inputStream.close();
        return "success";
    }

    @ApiOperation("Excel導出使用module")
    @GetMapping("export")
    public void export(HttpServletResponse response) throws IOException {
        List<UserWriteModule> userWriteModules = userMapper.exportList(new QueryWrapper().select("*"));
        ExcelUtils.exportModule("用戶信息",response,UserWriteModule.class,userWriteModules);
    }


    /**
     * 不使用module
     * @param response
     * @throws IOException
     */
    @ApiOperation("Excel導出不適用module")
    @GetMapping("exportMap")
    public void exportMap(HttpServletResponse response) throws IOException {
        List<UserWriteModule> userWriteModules = userMapper.exportList(new QueryWrapper().select("*"));
        ExcelUtils.exportMap("用戶信息",response,getHeadList(),userWriteModules);
    }



    public List<List<String>> getHeadList(){
        List<List<String>> headList = new ArrayList<>();
        List<String> dataHead = new ArrayList<>();
        dataHead.add("用戶姓名");
        dataHead.add("年齡");
        dataHead.add("性別");
        dataHead.add("地址");
        dataHead.add("手機號");
        dataHead.add("興趣");
       dataHead.forEach(s -> {
           ArrayList<String> objects = new ArrayList<>();
           objects.add(s);
           headList.add(objects);
       });
       return headList;
    }

    @ApiOperation("查詢列表")
    @GetMapping("get")
    public Object get(@RequestParam  String name){
        return userService.list(Wrappers.<User>lambdaQuery().eq(User::getUserName,name));
    }

}
相關文章
相關標籤/搜索