Import and export of Excel documents used by HuTool tools

Import and export of Excel documents used by HuTool tools


Preface

In daily work and development, the import and export of Excel is indispensable. If you write the corresponding import and export method yourself, it will be very cumbersome. This article uses the Excel import and export function implemented by Hutool tools, which can greatly reduce future development Import and export related operations in Excel.


Tip: The following is the content of this article, the following cases are for reference

1. What is Hutool?

      Hutool is a small and complete Java tool class library. Through static method encapsulation, it reduces the learning cost of related APIs and improves work efficiency. It makes Java have the elegance of a functional language and makes the Java language "sweet".

      The tools and methods in Hutool come from the meticulous crafting of each user. It covers all aspects of the underlying code of Java development. It is not only a tool for solving small problems in large-scale project development, but also an efficiency responsibility in small projects;

      Hutool is a friendly alternative to the "util" package in the project. It saves developers the encapsulation time of public classes and public tool methods in the project, enables development to focus on business, and avoids bugs caused by imperfect encapsulation.

Second, export the Excel file

   1. Introduce related dependencies

      There are only a handful of Java libraries for MS Office operations, and the more famous one is the Apache POI library. This library is extremely powerful, but it is not easy to use. Hutool encapsulates some common tools for POI, making it extremely simple to manipulate Excel and other files in Java. Hutool-poi is a package for Apache POI, so users need to import the POI library by themselves, Hutool does not import it by default.

      It should be noted that the poi-ooxml version of hutool-4.x must be higher than 3.17, and the poi-ooxml version of hutool-5.x must be higher than 4.1.2; the dependency information used in this article is shown in the following figure:

<!-- hutool工具类依赖-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.3</version>
</dependency>

<!--POI依赖,对office进行操作-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>

   2. The realization of Excel export function

      Hutool encapsulates the Excel write out as ExcelWriter. The principle is to package the Workbook object. After each call to the merge (merge cells) or write (write out data) method, it just writes the data to the Workbook, not the file, only the call Only after flush or close method will the file be written out. Due to the mechanism, the ExcelWriter object needs to be closed after the writing is completed, and the close method can be called to close it. At this time, the Workbook object resources will be released, otherwise the Workbook with data will always be resident in memory. The code is as follows:

@RequestMapping(EXCEL_DOWNLOAD)
public void excelExport(HttpServletResponse httpServletResponse) throws IOException {
    
    
UserDTO userDTO = new UserDTO();
List<UserDTO> userDTOS = userService.selectUserDOBatch(userDTO);
//通过hutool工具创建的excel的writer,默认为xls格式
ExcelWriter writer = ExcelUtil.getWriter();
//设置要导出到的sheet
writer.setSheet("表2");
writer.setSheet("表3");
//自定义excel标题和列名
writer.addHeaderAlias("id","用户ID");
writer.addHeaderAlias("userName","用户名");
writer.addHeaderAlias("loginPassword","密码");
writer.addHeaderAlias("email","邮箱");
writer.addHeaderAlias("createDate","数据创建日期");
//合并单元格后的标题行,使用默认标题样式
writer.merge(4,"用户基本信息表");
writer.renameSheet(0,"用户登录信息");
//一次性写出内容,使用默认样式,强制输出标题
writer.write(userDTOS,true);

httpServletResponse.setContentType("application/vnd.ms-excel;charset=utf-8");
//name是下载对话框的名称,不支持中文,想用中文名称需要进行utf8编码
String excelName = "用户基本信息表";
//excelName = new String(excelName.getBytes(),"utf-8");
excelName = URLEncoder.encode(excelName, "utf-8");
httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + excelName +".xls");

//将excel文件信息写入输出流,返回给调用者
ServletOutputStream excelOut = null;
try {
    
    
excelOut = httpServletResponse.getOutputStream();
writer.flush(excelOut,true);
} catch (IOException e) {
    
    
e.printStackTrace();
}finally {
    
    
writer.close();
}
IoUtil.close(excelOut);
}

      The above exported Excel format is .xls. If you want to export an excel file in .xlsx format, you only need to modify the corresponding location code shown in the figure above. The modification code is:

//设置返回excel的格式为xlsx
httpServletResponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
httpServletResponse.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("用户信息表","utf-8") + ".xlsx");

      The generated excel file is as follows:

Insert picture description here

Second, export the Excel file

   1. Excel Read-ExcelReader

      The import of Excel files is divided into three situations:

      1. Read all rows and columns in Excel, all expressed in lists

ExcelReader reader = ExcelUtil.getReader("d:/aaa.xlsx");
List<List<Object>> readAll = reader.read();

      2. Read as a Map list, the default first line is the title row, the key in the Map is the title, and the value is the cell value corresponding to the title.

ExcelReader reader = ExcelUtil.getReader("d:/aaa.xlsx");
List<Map<String,Object>> readAll = reader.readAll();

      3. Read as a Bean list, the field name in the Bean is title, and the field value is the cell value corresponding to the title.

ExcelReader reader = ExcelUtil.getReader("d:/aaa.xlsx");
List<Person> all = reader.readAll(Person.class);

      This article uses the third method to implement the Excel import and read example, and the relevant code is as follows:

 @RequestMapping(READ_EXCEL)
    public void readExcel(){
    
    
        ExcelReader reader = ExcelUtil.getReader("H:\\user.xlsx");
        List<UserDTO> userDTOS = reader.readAll(UserDTO.class);
        //日志输出读取到的信息
        log.info(userDTOS.toString());
    }

       The code of the UserDTO class is as follows:

@Data
public class UserDTO {
    
    
    @NotNull(message = "用户id不能为空")
    private Integer id;

    @NotNull(message = "用户名不能为空")
    @Size(min = 4, max = 16, message = "用户名长度错误")
    private String userName;

    @NotNull(message = "密码不能为空")
    @Size(min = 4, max = 16, message = "密码长度错误")
    private String loginPassword;

    @NotNull(message = "邮箱不能为空")
    @Email(message = "邮箱格式错误")
    private String email;


    @NotNull(message = "日期不能为空")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private Date createDate;
}

Guess you like

Origin blog.csdn.net/qq_36403831/article/details/108715160