In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "how Java realizes the generation of pdf and Excel and the dynamic insertion and export of data". The editor shows you the operation process through an actual case. The method of operation is simple, fast and practical. I hope that this article "how to achieve the generation of pdf and Excel by Java and dynamic data insertion and export" can help you solve the problem.
I. Preface
The export and import of Excel and PDF is a problem that we often encounter in our work. It just so happens that the company's business has encountered this problem today. By the way, take notes in case we encounter the same problem next time and be at a loss.
The company has two needs:
Requirement 1. A form is given to assemble the checked data into the form and provide download function in PDF format.
Demand 2. Download the data in the form of Excel table.
2. Java realizes the function of generating PDF and dynamically inserting and exporting data. 1. The first step: PDF making template.
Because the software commonly used in PDF does not support editing, we first use WPS to edit in the form of Word to create the same style as customer requirements, and then directly save it as .pdf.
b. Change the name to .pdf form
c. At this time, you need to use a software called Adobe Acrobat DC. The specific operations are as follows:
Use Adobe Acrobat DC to open the PDF file we just renamed, and click the "more tools" button in the lower right corner
Go to the following page and click the "prepare 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 to one). After the configuration, you can save and write the following code.
2. The writing of code
Suppose we have written all the entity classes, the data is obtained through the front end, and the template location is named under the root directory of the E disk: vehicle maintenance approval form .pdf.
Import the jar package:
Com.itextpdf itextpdf 5.5.13
Realize generation of PDF, data insertion and 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 parser System.setProperty ("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); String filename= "vehicle maintenance approval sheet .pdf"; String path= "eVV /"; 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 form reader = new PdfReader (path+ "/" + filename); / / 3 generate a new pdf ps = new PdfStamper (reader, os) based on the form; / / 4 get pdf form AcroFields form = ps.getAcroFields () / / 5 add a Chinese font to the form. Here the system font is used. If it is not set, Chinese may not be able to display BaseFont bf = BaseFont.createFont ("C _ Rank _ WINDOWSGINDOWINDOWSGANG _ SIMSUN.TTC _ Magi 1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); form.addSubstitutionFont (bf); / / 6 query data = Map data = new HashMap (); 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 traversing data assigns for (String key: data.keySet ()) {form.setField (key,data.get (key). ToString ()) to the pdf form form. } ps.setFormFlattening (true); log.info ("* PDF exported successfully * *") } 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;} II. Java realizes Excel generation and data insertion and export.
This is relatively simple, directly on the code (assuming your entity class, query and so on have been written) Note: the entity class is your own data entity class and the corresponding entity class in the table when you export. A summary of 100 intermediate and advanced interview questions in Java
Let's take a real corporate business as an example (an Excel export function that statistics the information of epidemic registrants)
a. The header corresponds to the entity class ExportYqfkdj.java
Import lombok.Data;/** * description: * @ author: zhouhong * @ version: V1.0.0 * @ date: 3:05:54 on January 14, 2021 * / @ Datapublic class ExportYqfkdj {/ * * serial number * / private Integer xuhao; / * * name * / private String xingming; / * document number * / private String zjhm / * contact telephone number * / private String lxdh; / * whether the applicant's workplace * / private String sqrGzdw; / * has come into contact with suspected cases * / private String sfjcgysbl; / * whether currently living with home quarantine personnel * / private String sfyjjglrytz / * current status * / private String dqzt; / * * current health status * / 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 list = new ArrayList (); try {/ * query export information * / result = getYqfkMhCXQuery (yqfkdjBean); SimpleDateFormat df = new SimpleDateFormat ("yyyyMMddhhmmssSSS"); for (int I = 0) I < result.getTotalcount (); iTunes +) {ExportYqfkdj dmKhfwdcDtjlZxDto = new ExportYqfkdj (); dmKhfwdcDtjlZxDto = ObjectUtil.parsePojo (result.getResults (). Get (I), ExportYqfkdj.class); dmKhfwdcDtjlZxDto.setXuhao (I + 1); list.add (dmKhfwdcDtjlZxDto);} String filepath = "String filepath / 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 * / private List head () {List list = new ArrayList (); List head0 = new ArrayList (); head0.add ("serial number"); List head1 = new ArrayList (); head1.add ("name"); List head2 = new ArrayList (); head2.add ("document number"); List head3 = new ArrayList () Head3.add ("contact phone"); List head4 = new ArrayList (); head4.add ("work place"); List head5 = new ArrayList (); head5.add ("contact with suspected cases"); List head6 = new ArrayList (); head6.add ("whether living with quarantined persons"); List head7 = new ArrayList (); head7.add ("current status"); List head8 = new ArrayList () Head8.add ("current health status"); List head9 = new ArrayList (); head9.add ("body temperature (°C)"); List head10 = new ArrayList (); head10.add ("current address"); List head11 = new ArrayList (); head11.add ("current address"); List head12 = new ArrayList (); 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 ") / / output file os.write (buffer); os.flush (); os.close ();} catch (Exception e) {e.printStackTrace (); log.info (YqfkdjUtils.Cytx.DCSB); throw e;}} this is the end of the content about "how Java implements the generation of pdf and Excel and dynamic data insertion and export". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.