“This is the 19th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

👨🎓 Author: Bug Bacteria

✏️ blog: CSDN, Nuggets, etc

💌 public account: Magic House of the Circle of the Apes

🚫 special statement: original is not easy, reprint please attach the original source link and this article statement, thank you for your cooperation.

🙏 Copyright notice: part of the text or pictures in the article may come from the Internet or Baidu Encyclopedia, if there is infringement, please contact bug bacteria processing.

Hi, family. I’m the bug. Here I go again. Today we are going to talk about something, OK, and we will continue the Series of articles on SpringBoot. Hope to help more beginners quickly start!

In the process of reviewing articles, if you think the articles are helpful to you at all, please don’t be too mean with your likes and bravely light up the articles 👍. Your likes (collect ⭐️+ pay attention to 👨 port + message board) are the best encouragement and support for bugs on my creation path. Time does not abandon 🏃🏻♀️, creation stopped 💕, refueling 🏻

One, foreword

In the last issue, we realized batch import and successful storage of Excel spreadsheet data through the integration of EasyPOI, right? If you read my article halfway, I have to ask you to browse the first two periods. My content teaching is progressive. It will not be large nor will it be completely fruitless. Therefore, I will start from my first issue “Preparation of integrating EasyPOI to achieve Excel import and export”.

This issue, I will take you to continue to explain how to achieve excel export through easyPOI, probably many friends have written, but the idea is sure to have some deviation, maybe take a look at mine, for you, maybe there is a big trigger in the idea, then we start today’s content? Are you all ready?

Add dependencies

Afraid of students directly see my article, so the environment configuration or mention a mouth, save unnecessary misleading.

Introduce easyPOio dependencies into the project’s POM files.

<! - easypoi dependence, Afterturn </groupId> <artifactId>easypoi-spring-boot-starter</artifactId> The < version > 4.2.0 < / version > < / dependency >Copy the code

Third, excel export

Step 1: Define an Excel export class

Let’s define an export VO first, so that we can customize the length and width of each exported field. For example, I judge each field according to the data length, add width attribute to each field in turn, and define the display length of each field.

The specific code is as follows:

Import.java

package com.example.demo.vo.ExcelUser; import cn.afterturn.easypoi.excel.annotation.Excel; import com.example.demo.entity.UserEntity; import lombok.Data; import java.io.Serializable; /** * excel import user parameter ** @author luoYong * @version 1.0 * @date 2022/2/15 14:34 */ @data public class ExportUser implements Serializable { private static final long serialVersionUID = 1L; /** * @excel is used for a field, the description of the column * @param name column name * @param orderNum subscript, starting from 0. */ @excel (name = "name ", width = 10.0) private String name; @excel (name = "age ", width = 10.0) private Integer age; @excel (name = "sex ", width = 5.0) private String sex; @excel (name = "address ", width = 30.0) private String address; @excel (name = "user description ", width = 20.0) private String describes; Public ExportUser() {} public ExportUser(UserEntity user) {this.name = user.getName(); this.age = user.getAge(); this.address = user.getAddress(); this.sex = user.getSex(); this.describes = user.getDescribes(); }}Copy the code

Step 2: Add an export class to the controller

UserController.java

The specific code is as follows:

@getMapping ("export") @apiOperation (value = "excel export", Public void exportUsers(HttpServletResponse Response) {userService.exportUsers(response); }Copy the code

Step 3: Define an export interface

UserServeice.java

The specific code is as follows:

*/ void exportUsers(HttpServletResponse Response);Copy the code

Step 4: Implement the export interface (core)

UserServeiceImpl.java

Specific code implementation is as follows: for your reference only, you modify according to the actual needs of your project, I just give you a demonstration, well, the basic is the following common Settings, nothing else.

*/ @overridePublic void exportUsers(HttpServletResponse Response) {try {List<UserEntity>  users = this.list(); Responsetheader (" content-type ", "application/vnd.ms-excel"); // fileName String fileName = "student information table.xls "; //sheet name String sheetName = "sheetName "; fileName = new String(fileName.getBytes(), "ISO-8859-1"); Responsetheader (" Content-disposition ", "attachment; filename=" + fileName); ServletOutputStream out = Response.getOutputStream (); // Set the excel parameter ExportParams params = new ExportParams(); // Set the sheet name params.setSheetName(sheetName); // Set the title params.setTitle(" student info table "); // Convert to the corresponding type; Otherwise, an error will be reported, although it can be exported successfully. List<ExportUser> exportUsers = changeType(users); / / import excel Workbook Workbook. = ExcelExportUtil exportExcel (params, ExportUser. Class, exportUsers); / / write workbook. Write (out); } catch (Exception e) { e.printStackTrace(); }}Copy the code

Step 5: Convert the UserEntity class to the ExportUser class

UserServeiceImpl.java

The specific implementation code is as follows: for your reference only

Vo ** @param users user set */ private List<ExportUser> changeType(List<UserEntity> users) {List<ExportUser> res = new ArrayList<>(); for (UserEntity user : users) { ExportUser exportUser = new ExportUser(user); res.add(exportUser); } return res; }Copy the code

Step 6: The browser calls the interface

In your browser’s address bar enter the export interface url: http://localhost:8080/user/export and then the keyboard enter, you will see, the browser left, download window will pop up a excel, this means that it has been written to excel success.

Screenshot of actual browser download:

After the download is completed, we will open the Excel file and check whether the file title, field name, field length and file name set in your code have been set successfully.

The actual screenshot after the Excel file is exported is as follows:

As you can see, the above screenshot has proved that the export method is completely correct. All the Settings are set, such as the length of each field, which is displayed according to the width property I set, which is nice.

Postman can also be used to call the export interface, which is as FOLLOWS: enter the URL and request mode, and then click [Send and Download].

However, the prompt to save to the local is a file named [response.xls], which is not named after fileName I set, I feel bad, I am sure this is not correct.

When I opened the file, I also found that there was no data from my list() query. It was just an empty Excel table, which I expected. But curious, why isn’t the data being written? Or am I opening Postman the wrong way? If you have encountered this problem and solve similar problems, also ask to teach bug bacteria ah, exchange and study together oh.

. .

That’s all for this episode, and if you want to learn more, you can check out my top tips on how to accumulate a little weird knowledge every day, and over time, you can become a person you respect. Well, I’ll see you next time

Four, the past popular recommendation

  • Springboot series (16) : Integrated easyPOI implementation of Excel import and export (preparation)

  • Springboot series (16) : Integrated EasyPOI to achieve Excel import function

  • Springboot series (15) : AOP implements custom annotations for business logging! Have you ever played?

  • Springboot series (14) : Redis Zero-based teaching, you deserve it!

  • Springboot Series (thirteen) : How to project integrated Swagger online interface documentation, will you?

  • Springboot series (12) : How to code to send email reminders, have you written?

  • . .

If you want to learn more, you can pay attention to the bug bug column “SpringBoot Zero-based Introduction”, from scratch, from zero to one! Hope I can help you.

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

☘️ Be who you want to be, there is no time limit, you can start whenever you want,

🍀 You can change from now on, you can also stay the same, this thing, there are no rules to speak of, you can live the most wonderful yourself.

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

💌 If this article is helpful to you, please leave a like! (# ^. ^ #);

💝 if you like the article shared by bug fungus, please give bug fungus a point of concern! The danjun ‘ᴗ, you guys will have a cameo appearance with you.

💗 if you have any questions about the article, please also leave a message at the end of the article or add a group [QQ communication group :708072830];

💞 In view of the limited personal experience, all views and technical research points, if you have any objection, please directly reply to participate in the discussion (do not post offensive comments, thank you);

💕 copyright notice: original is not easy, reprint please attach the original source link and this article statement, all rights reserved, piracy will investigate!! thank you