“This is the 20th 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 few sessions, we mainly talked about how to integrate EasyPOI to implement excel import and export functions, right? I don’t know how you have mastered it. If you still have questions about any of the following articles, please ask more questions. Ha ha ha, although I am not a big guy, I will try my best to teach each other and learn to fill in the gaps together.
-
How does Springboot integrate with EasyPOI
-
Integrated easyPOI to achieve excel import
-
Integrated EasyPOI to achieve excel export
-
Integrated easyPOI to export multiple data in word template
-
Integrated easyPOI to realize word template image export
However, in daily life, besides exporting Excel, it is very likely to be exposed to import and export of Word, PDF and other document export services in other formats, such as exporting data to Word documents for local download. One of the most common application scenarios is exporting user personal files.
Scenario: It is a process in which personal data is automatically filled into a Word template, and then exported into a Word document instead of manual filling. I have touched this requirement before when DEVELOPING the PERSONNEL OA system, which is quite interesting, so today I plan to lead you to explore from zero, and realize the function of exporting multi-page data from a single Word template, ok?
Next, I will begin to speak, the students may have to listen carefully oh ~
2. Introduce POM dependencies
Because EasyPoi can easily pass a Word template, and then generate the word document we want by filling the template. So today we are still based on easyPOI to achieve word document export.
<! - easypoi dependence, Afterturn </groupId> <artifactId>easypoi-spring-boot-starter</artifactId> The < version > 4.2.0 < / version > < / dependency >Copy the code
Three, to achieve word export
1. Define a Word template file
I’ll do it as a user class, so I’ll create a table in Word that will output the details of a user or all users. So I specified the following word template file:
2. Name the template
When you do template autofill, you have to assign values by unique names, so you need to do this in your Word template, and the value is directly {{name}}, where name is the name of the field that you give the value to.
In a nutshell, {{}} represents an expression and is evaluated according to the data in the expression.
For example:
3. Add word export method for Controller
Let’s first define a Word document export method, the purpose is to provide a port, easy to test through the browser access.
/**
* word文档导出
*/
@GetMapping("export-word")
@ApiOperation(value = "word文档导出", notes = "word文档导出")
public void exportUsersToWord(HttpServletResponse response) throws Exception {
userService.exportUsersToWord(response);
}
Copy the code
You don’t need any return values or arguments, you just need to carry the HttpServletResponse that you requested when you called the interface
4. Define the import interface
/** * word document export */ void exportUsersToWord(HttpServletResponse Response) throws Exception;Copy the code
5. Implement export method (core)
The following export implementation class is key, we can directly use easyPOi provided exportWord07() method, which will be your data assignment into the specified Word template. Please refer to the details I wrote:
The specific code Settings are as follows:
/** * word document export */ @override public void exportUsersToWord(HttpServletResponse Response) throws Exception {// Prepare to export data List<Map<String, Object>> listUsers = new ArrayList<>(); List<UserEntity> users = this.list(); Users. forEach(user -> {// a map equals a template map <String, Object> map = new HashMap<>(); map.put("name", user.getName()); map.put("age", user.getAge()); map.put("sex", user.getSex()); map.put("address", user.getAddress()); map.put("describes", user.getDescribes()); / / add listUsers. Add (map); }); / / export word and specify the word export template XWPFDocument doc. = WordExportUtil exportWord07 (". / template/users to export template. Docx ", listUsers); / / set the coding format response. SetCharacterEncoding (StandardCharsets. UTF_8. Name ()); // Set the content type response.setContentType("application/octet-stream"); // Set the header and file name. response.setHeader("Content-Disposition", "attachment; Filename =" + URLEncoder. Encode (" student.docx ", standardCharsets.utf_8.name ())); / / write doc. Write (response. GetOutputStream ()); }Copy the code
The first thing you need to notice is that normally word documents are placed on a specific server location or in a project. I created a file called Template folder, specifically used to store the specified template class files, otherwise directly reference the local absolute location file, change a computer or other colleagues local run is not very convenient.
Here is the actual screenshot of the template folder location of my project:
Second, specifying the download file name and the request type for response means telling the browser what kind of thing you’re doing, so set Response. setContentType(“application/octet-stream”).
Next word export method we have written, the rest is to carry out the corresponding test.
6. Browser test interface
We open the browser, enter the address of the interface we just exposed in Controller in the address bar:
Like me: http://localhost:8080//user/export-word you for a visit at your interface address.
You can see that a file is being downloaded, and the rest is to see if the content has been backfilled.
As shown in the figure above, you can see that the data filled in is exactly a piece of data from the database, which means that there is no problem with exporting word template method.
A map corresponds to a Word template document. There are 9 users in total, but there are 10 pages in total. The last page is blank. If there are friends who know, welcome to exchange, learn from each other ~
However, under normal circumstances, we will not write all the data in Word. Generally, we will query the data with the unique ID of the user and then export it, so that there is only one user information! This depends on the demand, some may be exported all content, depending on the user demand is what, but this is certainly very good adjustment ah, can also be more close to the user’s idea, export how many, by the user’s own control is good, some according to the page export, some according to the article export and so on.
Of course, there’s also the implementation of exporting all data from a template, which I’ll explain in the next installment.
. .
Well, 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 (16) : Integrated easyPOI to achieve Excel export function
-
Springboot series (16) : Integrated easyPOI to realize word template circulation export multiple data
-
Springboot series (16) : Integrated easyPOI word template image export
-
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