By: Slow Time source: cnblogs.com/Tom-shushu/p/14279357.html
A preface,
The export and import of Excel and PDF is a problem we often encounter in our work. It happened that our company encountered this problem today. By the way, I will make a note in case we encounter the same problem next time.
The company has two needs:
Requirement 1: a form is provided to assemble the found data into the form and provide PDF download function.
Requirement 2. Find out the data and download it in the form of Excel.
Java PDF generation and dynamic data insertion, export function
1, the first step: PDF template
Because PDF commonly used software does not allow editing, we first use WPS to edit in Word form to make the same style as the customer needs, and then directly save it as.pdf, as shown in the picture below:
A. Lord inside make template
B. Change the name to. PDF
C. At this time, you need to use a software called Adobe Acrobat DC, the specific operations are as follows:
Open the PDF file with Adobe Acrobat DC and click on the “More Tools” button in the lower right corner
Go to the page below and click the “Prepare form” button
D. Next, you need to configure your data source in detail
Data source: your code entity class in the corresponding data (note that the fields must be one-to-one correspondence), configuration can be saved for the following code writing work.
2. Code writing
Let’s assume that our entity class has been written, the data is passed in and retrieved from the front end, and the template location is in the root directory of drive E named: 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 >Copy the code
Realization of PDF generation, data insertion, 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.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(); Reader = new PdfReader(path+ "/"+filename); Ps = new PdfStamper(reader, OS); // 4 Obtain the PDF form AcroFields form = ps.getAcrofields (); // add a Chinese font to the form. If I don't set it, Chinese may not be able to display the BaseFont bf = BaseFont. CreateFont (" C: / WINDOWS/Fonts/SIMSUN. TTC, 1 ", the BaseFont. IDENTITY_H, BaseFont. EMBEDDED); form.addSubstitutionFont(bf); / / 6 query data = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Map < String, the String > data = new HashMap < String, the 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()); For (String key: data.keyset ()) {form.setfield (key,data.get(key).tostring ()); } ps.setFormFlattening(true); The info (" * * * * * * * * * * * * * * * * * * * PDF export success * * * * * * * * * * * * * * * * * * * * * * * "); } the catch (Exception e) {log. The error (" * * * * * * * * * * * * * * * * * * * PDF export failure * * * * * * * * * * * * * * * * * * * * * * * "); e.printStackTrace(); } finally { try { ps.close(); reader.close(); os.close(); } catch (Exception e) { e.printStackTrace(); } } return null; }Copy the code
3, test,
Third, Java Excel generation and data insertion, export
Note: The entity classes are your own data entity class and the corresponding entity class in the table that you exported. 100 Advanced Interview questions in Java
Let’s take an example from a real corporate business (an Excel export feature that collects information about epidemic registrants)
A. The table header corresponds to the entity class exportyQFkdj.java
import lombok.Data; /** * description: * @author: zhouhong * @version: V1.0.0 * @date: */ @data public class ExportYqfkdj {/** ** private Integer xuhao; /** * name */ private String xingming; /** * private String ZJHM; /** * contact number */ private String LXDH; /** * private String sqrGzdw; /** * Contact with suspected cases */ private String sfjcgYSbl; Private String sFYjjGLrytz; /** * Private String sFYjjglrytz; /** * private String DQZT; /** * Current health status */ private String DQJKZT; /** * private String DQTW; /** * private String DQSZDZ; /** * private String DQJZDZ; /** * private String TJSJ; }Copy the code
B.S ervice layer
@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 the exported 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:/ COVID-19 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; } /** * @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 (" name "); List<String> head2 = new ArrayList<String>(); Head2. add(" iD "); 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 (" Living with quarantined person "); List<String> head7 = new ArrayList<String>(); Head7.add (" current state "); List<String> head8 = new ArrayList<String>(); Head8.add (" Current health status "); List<String> head9 = new ArrayList<String>(); Head9. Add (" body temperature (° C) "); List<String> head10 = new ArrayList<String>(); Head10.add (" current address "); List<String> head11 = new ArrayList<String>(); Head11.add (" current address "); List<String> head12 = new ArrayList<String>(); Head12.add (" Submit 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; }Copy the code
Arthur c. ontroller layer
@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 = "COVID-19 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"); // Output file os.write(buffer); os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); log.info(YqfkdjUtils.Cytx.DCSB); throw e; }}Copy the code
test
The PDF and Excel functions have been generated, inserted, and exported.
Refer to the link: www.cnblogs.com/wangpeng007…
Recent hot articles recommended:
1.1,000+ Java Interview Questions and Answers (2021)
2. Don’t use if/ else on full screen again, try strategy mode, it smells good!!
3. Oh, my gosh! What new syntax is xx ≠ null in Java?
4.Spring Boot 2.6 is out with a lot of new features.
5. “Java Development Manual (Songshan version)” the latest release, quick download!
Feel good, don’t forget to click on + forward oh!