[JasperReports notes 01] Jasper Studio report development tool installation and use Java to fill template file content

This article mainly introduces how to install the Jasper Studio report development tool and use Java to fill the content of the template file.

Table of contents

1. Install the Jasper Studio tool

1.1. Download the report development tool

1.2. Tool interface introduction

(1) Start the tool

(2) Create a project

Two, make Jasper template file

2.1. Jasper file composition area introduction

2.2. Make template files

3. Use Java to fill data

3.1. Introducing dependencies

3.2. Create the JasperReportsUtil tool class

3.3, test controller class

3.4. Place the Jasper template file

3.5, run the test


1. Install the Jasper Studio tool

1.1. Download the report development tool

JasperReport provides a development tool specially used to make report template files, called: Jasper Studio, the official download address is: https://community.jaspersoft.com/community-download , enter the download interface, as shown below:

Click the download button, a prompt box will pop up, click continue to jump to the download details interface: https://community.jaspersoft.com/project/jaspersoft-studio/releases , as shown below:

In the download details interface, you can download files in various formats, such as: exe, zip, tgz, etc. Here I choose the zip file and click to download. It should be noted that when downloading, you will be prompted to register a JasperReports community account. We can register one with our own email address. Unzip the downloaded zip archive to your working directory. After decompression, you will get a jaspersoftstudio directory, as shown below:

There is a Jaspersoft Studio.exe file in this directory, double-click this file to start the JasperReports reporting tool.

1.2. Tool interface introduction

(1) Start the tool

Double-click the Jaspersoft Studio.exe file to start the JasperReports report tool, as shown in the following figure:

The picture above is the welcome interface after startup, it looks a bit like the eclipse development tool, right? That's right, Jasper Studio is developed based on Eclipse. It can be used alone or added to the Eclipse development tool as an Eclipse plug-in.

(2) Create a project

Select [File-->New-->Jasper Report] in the upper left corner to create a report project, as shown below:

In the pop-up box, just select the template file you need. Generally speaking, you choose an A4 blank template, or an A4 blank template in the horizontal direction, and the rest is to design the template file yourself.

Enter the project name, select the data source, etc., which can be omitted here, just click next for a fool, and finally click Finish.

After the project is successfully created, you will enter the working area of ​​Jasper Studio. The Jasper working area is roughly divided into the following parts:

At this point, the Jasper Studio tool is installed, and the basic work area is also known, then you can start making your own template files.

Two, make Jasper template file

2.1. Jasper file composition area introduction

You can see that there are many components in the main report area of ​​Jasper Studio, as shown in the following figure:

Jasper divides the template file into the above components. Each component has different meanings. The function of each part is as follows:

  • Title area: This area will only be displayed on the first page of the template file, and will not be displayed from the second page, mainly defining the title content of the file.
  • Page Header area: This area starts from the second page, and the header information displayed on each page is displayed at the top of each page.
  • Column Header area: When we use the Table component, the Column Header area will take effect, and the column header of the table it represents will be displayed on each page.
  • Detail area: This area is the area where the content is actually displayed, and there can be multiple Detail areas.
  • Column Footer area: When we use the Table component, the Column Footer area will take effect, and the column end of the table it represents will be displayed on each page.
  • Page Footer area: This area starts from the second page, and the footer information displayed on each page is displayed at the bottom of each page.
  • Summary area: This area represents the total area and will only be displayed at the end of the last page.

It doesn't matter if you don't know these things now. In the following articles, I will demonstrate the role of each area by making some template files. Here is a simple template file to demonstrate how to fill the template file with data through Java.

2.2. Make template files

First delete the unnecessary area in the file, select the element to be deleted, and right-click Delete:

Only the Title and Detail areas are reserved, and the effect after deletion is as follows:

From the component element bar on the right, select the [Text Field] component and drag it to the Title area, as follows:

Select the component you just added, and you can edit its style, such as: font, font size, alignment, etc., color and other attributes. In the [Paramater] in the [outline] area, right click to create a parameter, as shown below:

Then in [Properties] in the lower right corner area, enter the parameter name and the Java data type corresponding to the parameter, as follows:

After the parameters are created, we can select the [Text Field] component we dragged to the Title area again, and set the parameter value name used by the component in the [Properties] attribute area in the lower right corner.

The Parameters parameter used here can be directly passed a Map object through Java code for data filling and replacement. In this way, several more test parameters can be created. The final simple template is as follows:

Now that the template file is made, you can use the Java language to write the data that needs to be filled into the template file.

3. Use Java to fill data

3.1. Introducing dependencies

In actual development, it is generally a Web engineering project, so here is a project environment built using the SpringBoot project, which needs to introduce JasperReports-related dependencies, as follows:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.gitcode.demo</groupId>
    <artifactId>jasper-demo</artifactId>
    <version>1.0.0</version>

    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.3.5.RELEASE</version>
    </parent>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- JasperReports 报表开发所需依赖 START -->
        <!-- https://mvnrepository.com/artifact/net.sf.jasperreports/jasperreports -->
        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>6.20.0</version>
            <exclusions>
                <!--
                    排除自带的itext依赖,因为自带的itext版本是 2.1.7.js10
                    这个版本在中央仓库里面没有,无法下载
                -->
                <exclusion>
                    <groupId>com.lowagie</groupId>
                    <artifactId>itext</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- 引入itext依赖,因为JasperReports中使用了itext操作PDF -->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>
        <!-- JasperReports 报表开发所需依赖 END -->
        <!--
            引入 poi 依赖,因为 jasper 底层操作excel使用的是poi组件
        -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
    </dependencies>
</project>

3.2. Create the JasperReportsUtil tool class

In order to facilitate the operation of Jasper reports, the report processing is carried out in a unified class here, and the code is as follows:

package com.gitcode.demo.util;

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.export.*;
import org.springframework.core.io.ClassPathResource;

import java.io.InputStream;
import java.util.Map;
import java.util.Objects;

/**
 * @version 1.0.0
 * @Date: 2023/8/7 14:14
 * @Author ZhuYouBin
 * @Description: JasperReports 工具类
 */
public class JasperReportsUtil {

    /**
     * 使用 JasperReports 生成报表文件
     * @param templatePath 模板文件路径及名称
     * @param fileName 生成的文件名称
     * @param fileType 生成的文件类型,例如: pdf、html、xls 等
     * @param parameters 传递到 jrxml 模板文件中的数据参数
     * @return 返回生成的报表文件路径
     */
    public static String generateReport(String templatePath, String fileName, String fileType, Map<String, Object> parameters) throws Exception {
        // 1、获取 jasper 模板文件【采用流的方式读取】
        ClassPathResource resource = new ClassPathResource(templatePath);
        InputStream in = resource.getInputStream();
        JasperReport jasperReport = (JasperReport) JRLoader.loadObject(in);
        // 2、将 parameters 数据参数填充到模板文件中
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JREmptyDataSource());
        // 3、按照指定的 fileType 文件类型导出报表文件
        if (Objects.equals("pdf", fileType)) {
            JasperExportManager.exportReportToPdfFile(jasperPrint, fileName + ".pdf");
        } else if (Objects.equals("xls", fileType)) { // 导出 xls 表格
            JRXlsExporter exporter = new JRXlsExporter();
            exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); // 设置导出的输入源
            exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(fileName + ".xls")); // 设置导出的输出源
            // 配置信息
            SimpleXlsReportConfiguration configuration = new SimpleXlsReportConfiguration();
            configuration.setOnePagePerSheet(true); // 每一页一个sheet表格
            exporter.setConfiguration(configuration); // 设置配置对象
            exporter.exportReport(); // 执行导出
        } else if (Objects.equals("xlsx", fileType)) {  // 导出 xlsx 表格
            JRXlsxExporter exporter = new JRXlsxExporter();
            exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); // 设置导出的输入源
            exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(fileName + ".xlsx")); // 设置导出的输出源
            SimpleXlsxReportConfiguration configuration = new SimpleXlsxReportConfiguration();
            configuration.setOnePagePerSheet(true); // 每一页一个sheet表格
            exporter.setConfiguration(configuration);
            exporter.exportReport(); // 执行导出
        } else if (Objects.equals("html", fileType)) {
            JasperExportManager.exportReportToHtmlFile(jasperPrint, fileName + ".html");
        }
        return null;
    }

}

3.3, test controller class

Write a TestController test controller, and then add the template data that needs to be filled in the code, as follows:

package com.gitcode.demo.web;

import com.gitcode.demo.util.JasperReportsUtil;
import net.sf.jasperreports.engine.util.JRResourcesUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0.0
 * @Date: 2023/8/10 21:13
 * @Author ZhuYouBin
 * @Description:
 */
@RestController
@RequestMapping("/api/report")
public class TestController {

    @GetMapping("/export")
    public String exportFile(String format) throws Exception {
        ClassPathResource resource = new ClassPathResource("MyFirstReport.jasper");
        String templatePath = resource.getPath();
        String fileName = "Jasper导出文件";
        /*
         创建传递到 Jasper 模板文件中的数据参数。
         注意:参数的 key 必须和 Jasper Studio 中创建的 Parameters 参数名称相同,否则匹配不上,无法填充数据。
         */
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("titleName", "This is a title.");
        parameters.put("userName", "Tom");
        parameters.put("sex", "man");
        parameters.put("age", "20");
        parameters.put("address", "everywhere.");
        // 执行导出操作
        return JasperReportsUtil.generateReport(templatePath, fileName, format, parameters);
    }

}

3.4. Place the Jasper template file

Compile the previously made Jasper template file. After compilation, a file with a [.jasper] suffix will be generated. This file is the template file we want, and we need to put this file in the [src/main/resources] resource directory of the project. ,As follows:

3.5, run the test

Start the project, open the browser to visit http://localhost:8080/api/report/export?format=pdf address, then the corresponding file will be generated in the project directory:

Open the file to view its contents, as shown below:

So far, the installation of the Jasper Studio report tool, the creation of a simple template, and the use of Java to fill the template file data have been introduced.

In summary, this article is over. It mainly introduces how to install the Jasper Studio report development tool and use Java to fill the content of the template file.

Guess you like

Origin blog.csdn.net/qq_39826207/article/details/132198182