One 、 preface

Excel、PDF Export of 、 Import is a common problem in our work , Just today, the company's business encountered this problem , By the way, take a note in case you're stuck with the same problem next time .

The company has two needs :

Need one 、 Given a form , Let's assemble the found data into a form and provide PDF Format download function .

Demand two 、 Look up the data to Excel Download it in the form of a form .

Two 、Java Realization PDF Data generation and data dynamic insertion 、 Export function

1、 First step :PDF Making templates

because PDF Common software does not support editing , Let's start with WPS With Word In the form of editing, making the same style as the customer needs , And then save it as .pdf The form is shown in the figure below :

a.Word Make templates inside

b. Change the name to .pdf form

c. We need to use one called :Adobe Acrobat DC Software for ( You can go whoring for nothing 7 God ^_^), The specific operation is as follows :

use Adobe Acrobat DC Open the one we just renamed PDF file , Click on the “ More tools ” Button

Go to the page below and click “ Prepare the form ” Button

d. Next, you need to configure your data source in detail

The data source is : The corresponding data in the entity class in your code ( Note that the fields must correspond one by one ), After configuration, you can save it and write the following code .

2、 Code writing ( Let's assume that we've written all our entity classes 、 The data is passed in from the front end 、 The template is located in E The name in the packing directory is : Vehicle maintenance approval form .pdf)
Import jar package :
<!-- PDF export -->
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
Implementation generation PDF、 Insert data into 、 export
 @RegisterToSMP(serviceDisplay = " Preview page PDF download ")
@RequestMapping(value = "/DM/gwclwxsq/qygl/exportPDF$m=query.service",method =RequestMethod.POST)
public String exportPdf(@RequestBody GwclwxsqBean gwclwxsqBean , HttpServletResponse response) throws UnsupportedEncodingException {
// 1. Specify the parser
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
String filename=" Vehicle maintenance approval form .pdf";
String path="e:/";
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;fileName="
+ URLEncoder.encode(filename, "UTF-8"));
OutputStream os = null;
PdfStamper ps = null;
PdfReader reader = null;
try {
os = response.getOutputStream();
// 2 Read in pdf Forms
reader = new PdfReader(path+ "/"+filename);
// 3 Generate a new pdf
ps = new PdfStamper(reader, os);
// 4 obtain pdf Forms
AcroFields form = ps.getAcroFields();
// 5 Add Chinese fonts to the form System fonts are used here . If it is not set , Chinese may not display
BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",
BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
form.addSubstitutionFont(bf);
// 6 Query data ================================================
Map<String, String> data = new HashMap<String, String>();
data.put("commitTime", gwclwxsqBean.getCommitTime());
data.put("driver", gwclwxsqBean.getDriver());
data.put("carId", gwclwxsqBean.getCarId());
data.put("carType", gwclwxsqBean.getCarType());
data.put("repairAddress", gwclwxsqBean.getRepairAddress());
data.put("repairCost",gwclwxsqBean.getRepairCost());
data.put("project", gwclwxsqBean.getProject());
data.put("fwbzzxfzrYj", gwclwxsqBean.getFwbzzxfzrYj());
data.put("fgldspYj", gwclwxsqBean.getFgldspYj());
data.put("remarks", gwclwxsqBean.getRemarks());
// 7 Traverse data to pdf Form table assignment
for (String key : data.keySet()) {
form.setField(key,data.get(key).toString());
}
ps.setFormFlattening(true);
log.info("*******************PDF Export succeeded ***********************");
} catch (Exception e) {
log.error("*******************PDF Export failed ***********************");
e.printStackTrace();
} finally {
try {
ps.close();
reader.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
3. test

Two 、Java Realization Excel Generation and data insertion 、 export

This is simpler , Go straight to the code ( Suppose your entity class 、 All the queries have been written ) Be careful : One entity class is your own data entity class, and the other is the corresponding entity class in the table when you export

Let's take a real company business as an example ( A statistical epidemic registration personnel information Excel Export function )

1. The header corresponds to the entity class ExportYqfkdj.java:
import lombok.Data;
/**
* description:
* @author: zhouhong
* @version: V1.0.0
* @date: 2021 year 1 month 14 Japan Afternoon 3:05:54
*/
@Data
public class ExportYqfkdj {
/**
* Serial number
*/
private Integer xuhao;
/**
* full name
*/
private String xingming;
/**
* ID number
*/
private String zjhm;
/**
* contact number
*/
private String lxdh;
/**
* Applicant's work unit
*/
private String sqrGzdw;
/**
* Have you ever been in contact with a suspected case
*/
private String sfjcgysbl;
/**
* Whether to live with the isolated people at home at present
*/
private String sfyjjglrytz;
/**
* current state
*/
private String dqzt;
/**
* The current state of health
*/
private String dqjkzt; /**
* Current body temperature
*/
private String dqtw;
/**
* Current address
*/
private String dqszdz;
/**
* Current residential address
*/
private String dqjzdz;
/**
* Submission time
* */
private String tjsj;
}
b.Service layer
 /**
* export
* @param yqfkdjBean
* @author zhouhong
* @return
* @throws Exception
*/
@Transactional(rollbackFor = { Exception.class })
public DataResult exporYqfkdj(YqfkdjBean yqfkdjBean) throws Exception {
DataResult result = new DataResult();
List<ExportYqfkdj> list = new ArrayList<ExportYqfkdj>();
try {
/* Query export information */
result = getYqfkMhCXQuery(yqfkdjBean);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmssSSS");
for (int i = 0; i < result.getTotalcount(); i++) {
ExportYqfkdj dmKhfwdcDtjlZxDto = new ExportYqfkdj();
dmKhfwdcDtjlZxDto = ObjectUtil.parsePojo(result.getResults().get(i), ExportYqfkdj.class);
dmKhfwdcDtjlZxDto.setXuhao(i + 1);
list.add(dmKhfwdcDtjlZxDto);
}
String filepath = "D:/ Epidemic prevention and control information " + df.format(new Date()) + ".xlsx";
if (System.getProperty(YqfkdjUtils.Wjdz.NAME).toLowerCase().startsWith(YqfkdjUtils.Wjdz.LI)
|| System.getProperty(YqfkdjUtils.Wjdz.NAME).toLowerCase().startsWith(YqfkdjUtils.Wjdz.LIN)) {
filepath = "/home/Tomcat/temp/" + df.format(new Date()) + ".xlsx";
}
EasyExcel.write(filepath, ExportYqfkdj.class).head(head()).sheet().doWrite(list);
result.setResults(list);
result.setSuccess(true);
result.setMsg(filepath);
} catch (Exception e) {
result.setSuccess(false);
result.setMsg(YqfkdjUtils.Cytx.DCSB);
e.printStackTrace();
throw e;
}
return result;
}
/**
* Epidemic prevention and control information export header
* @author zhouhong
* @return List<List<String>>
*/
private List<List<String>> head() {
List<List<String>> list = new ArrayList<List<String>>();
List<String> head0 = new ArrayList<String>();
head0.add(" Serial number ");
List<String> head1 = new ArrayList<String>();
head1.add(" full name ");
List<String> head2 = new ArrayList<String>();
head2.add(" ID number ");
List<String> head3 = new ArrayList<String>();
head3.add(" contact number ");
List<String> head4 = new ArrayList<String>();
head4.add(" Work unit ");
List<String> head5 = new ArrayList<String>();
head5.add(" Contact with suspected cases ");
List<String> head6 = new ArrayList<String>();
head6.add(" Whether to live with quarantine personnel ");
List<String> head7 = new ArrayList<String>();
head7.add(" current state ");
List<String> head8 = new ArrayList<String>();
head8.add(" The current state of health ");
List<String> head9 = new ArrayList<String>();
head9.add(" Temperature (°C)");
List<String> head10 = new ArrayList<String>();
head10.add(" Current address ");
List<String> head11 = new ArrayList<String>();
head11.add(" Current residential address ");
List<String> head12 = new ArrayList<String>();
head12.add(" Submission time ");
list.add(head0);
list.add(head1);
list.add(head2);
list.add(head3);
list.add(head4);
list.add(head5);
list.add(head6);
list.add(head7);
list.add(head8);
list.add(head9);
list.add(head10);
list.add(head11);
list.add(head12);
return list;
}
c.Controller layer
 @RegisterToSMP(serviceDisplay = " Epidemic prevention and control query export ")
@RequestMapping(value = "/DM/yqfkdj/gr/yqfkdjdc$m=export.service", method = RequestMethod.POST)
public void exportKhfxxx(@RequestBody YqfkdjBean yqfkdjBean, HttpServletResponse resp) throws Exception {
DataResult result = new DataResult();
try {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmssSSS");
result = yqfkdjService.exporYqfkdj(yqfkdjBean);
String filepath = result.getMsg().replace("\"", "");
File file = new File(filepath);
String filename = " Epidemic prevention and control information " + df.format(new Date()) + ".xlsx";
InputStream fis = new BufferedInputStream(new FileInputStream(filepath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
resp.reset();
resp.setHeader("Content-Disposition",
"attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("gbk")));
resp.setHeader("Content-Length", "" + file.length());
OutputStream os = new BufferedOutputStream(resp.getOutputStream());
resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
// The output file
os.write(buffer);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
log.info(YqfkdjUtils.Cytx.DCSB);
throw e;
}
}
d. test

It's all done PDF and Excel Generation 、 Insert 、 Export function .

Reference link :https://www.cnblogs.com/wangpeng00700/p/8418594.html

Java Realization PDF and Excel Generation and data dynamic insertion and export of more related articles

  1. java Use POI Realization Excel Bulk import data

    1. preparation 1.1 Create a one-to-one correspondence between the template header and the database table fields , Examples are as follows 1.2 Put the template into the project , As shown in the figure below : 2. Front page 2.1 Use the hyperlink to provide the template download address <html lang="zh ...

  2. Java operation pdf And excel

    java  operation pdf Components   itextpdf <dependency> <groupId>com.itextpdf</groupId> <artifactId ...

  3. jsp request java return pdf、excel And word

    1, return pdf Key code /** * @todo * @param * @date 2019 year 3 month 8 Japan * @author yanan */ @RequestMapping("/getPdf& ...

  4. poi export excel, Dynamic assembly of header data

    /* * First step : Assemble the header and data */ // Put more than one sheet Set List<Map<String,Object>> datas = new ArrayList<Map ...

  5. C# Database data dynamic insertion ( Reflection )

    /// <summary> /// To provide the MySqlDataReader Turn into T Type extension method /// </summary> public static class MySqlD ...

  6. Generate statistics and export Excel

    demand : Look at the statistical requirements in the table below The production scheduling center department needs to start from IT The technology department gets these statistics step : (1) Get a list of all the subsidiaries (2) Go through all the subsidiaries , Obtain the inventory information of each subsidiary (3) Traverse all inventory information , And inventory ...

  7. postman Upload excel,java Background read excel Generated to the specified location for backup , And the excel Add the data in to the database

    I'm going to upload a front-end web page recently excel, The ability to add data directly to the database .. Write a read here excel Of demo. First new springboot Of web project Guide pack , Read excel It can be used poi It can also be used. jxl, Here we use ...

  8. Java analysis OFFICE(word,excel,powerpoint) as well as PDF Implementation of the program and the development of bit by bit to share

    Java analysis OFFICE(word,excel,powerpoint) as well as PDF Implementation of the program and the development of bit by bit to share Here it is , Let's share our experiences and feelings before writing this article , All my feelings are condensed into one word , That's it :" pit &qu ...

  9. java operation office and pdf file java Read word,excel and pdf Document content

    In normal applications , Yes office and pdf Reading data from documents is a common function , Especially in many web In the application . So today, let's take a brief look at Java Yes word.excel.pdf File reading . This blog is just a simple explanation ...

  10. Java Upload and download excel、 analysis Excel、 Generate Excel

    In the process of software development, it is inevitable to upload and download in batches , It is also common to generate and save reports , Recently, group portal development uses Excel Template download ,Excel Generate , The successful completion of , Sort out this knowledge , Resource sharing , We hope to criticize and correct the shortcomings , At the end of the article ...

Random recommendation

  1. It's on the shelves before it's solved App stay iOS 9 It's a flashback problem ( to update : existing Hotfix)

    Latest updates :(2015.10.02) development environment : Delphi 10 Seattle OS X El Capitan v10.11 Use the following HotfixID: 30398, PAServer Hot ...

  2. c There are three ways to define the structure of language

    struct Structure name {    Member list :   ..... } Structural variable : Definition of structure type variable The definition of structure type variables is the same as that of other types of variables , However, the structure type needs to be defined in advance , So the structure ...

  3. android adopt HttpClient With the server JSON Interaction

    Through yesterday to HttpClient Learning from , It's encapsulated today HttpClient class The code is as follows : package com.tp.soft.util; import java.io.BufferedReader; i ...

  4. see MySQL The default encoding of the database

    see MySQL The default encoding of the database 1. Use status Command can display database related information , Examples are as follows : mysql> status;————–mysql Ver 14.12 Distrib 5.0.77 ...

  5. SpringMVC Basics -@RequestMapping

    @RequestMapping @RequestMapping Is an annotation used to process the request address mapping Can be used on a class or method .   Class definition : Provide preliminary request mapping information . Equivalent to the current WEB Root of application   method : ...

  6. On C++ How to use arrays gracefully

    C/C++ If a function takes an array as an argument , Then the array will degenerate into a pointer , If you define the following code : // Array arr The size of is unknown . int arrsize(int arr*) { cout << &q ...

  7. Codeforces 1045E. Ancient civilizations structure Computational geometry convex hull

    Link to the original text https://www.cnblogs.com/zhouzhendong/p/CF1045E.html 4K Code construction problem ,CF Bloody brutality ! Answer key First , If all the dots are the same color , Well, just a chrysanthemum . ...

  8. Front end foundation http agreement

    B-S Pattern : browser------>server BS Mode working process : The user is in browser Enter a URL Make sure you want to visit server browser send out post/get request to serv ...

  9. DevExpress Control method : Second articles barManager

    The title bar One .Bars 1.   hold BarManager After the component is added to the form , Three empty ones will be created automatically bars: The main menu ( Usually at the top of the form ). Top Toolbar . The status bar at the bottom of the form . 2.   Hide the vertical line on the left and the arrow on the right ...

  10. CountDownLatch And CyclicBarrier Use

    CyclicBarrier Use : Suppose there's only one scene : Each thread represents a runner , When the players are ready , Just started together , As long as one person is not ready , Everybody's waiting . CountDownLacth Use : He is often used in prison ...