当前位置: 代码网 > it编程>编程语言>Java > SpringBoot实现数据导入导出与报表生成的完整教程

SpringBoot实现数据导入导出与报表生成的完整教程

2026年04月12日 Java 我要评论
学习目标与重点提示学习目标:掌握spring boot数据导入导出与报表生成的核心概念与使用方法,包括数据导入导出的定义与特点、spring boot与数据导入导出的集成、spring boot与数据

学习目标与重点提示

学习目标:掌握spring boot数据导入导出与报表生成的核心概念与使用方法,包括数据导入导出的定义与特点、spring boot与数据导入导出的集成、spring boot与数据导入导出的配置、spring boot与报表生成的基本方法、spring boot的实际应用场景,学会在实际开发中处理数据导入导出与报表生成问题。

重点:数据导入导出的定义与特点spring boot与数据导入导出的集成spring boot与数据导入导出的配置spring boot与报表生成的基本方法spring boot的实际应用场景

数据导入导出概述

数据导入导出是java开发中的重要组件。

数据导入导出的定义

定义:数据导入导出是指将数据从一个系统导入到另一个系统,或从一个系统导出到另一个系统的过程。

作用

  • 实现数据的迁移。
  • 实现数据的备份。
  • 实现数据的共享。

常见的数据导入导出格式

  • csv:comma-separated values,逗号分隔值格式。
  • excel:microsoft excel格式。
  • json:javascript object notation,javascript对象表示法格式。
  • xml:extensible markup language,可扩展标记语言格式。

结论:数据导入导出是指将数据从一个系统导入到另一个系统,或从一个系统导出到另一个系统的过程,作用是实现数据的迁移、备份、共享。

数据导入导出的特点

定义:数据导入导出的特点是指数据导入导出的特性。

特点

  • 易用性:数据导入导出提供易用的编程模型。
  • 高效性:数据导入导出提供高效的数据处理。
  • 可扩展性:数据导入导出可以扩展到多个应用程序之间的数据通信。
  • 可靠性:数据导入导出提供可靠的数据传输。

结论:数据导入导出的特点包括易用性、高效性、可扩展性、可靠性。

spring boot与数据导入导出的集成

spring boot与数据导入导出的集成是java开发中的重要内容。

集成apache poi的步骤

定义:集成apache poi的步骤是指使用spring boot与apache poi集成的方法。

步骤

  1. 创建spring boot项目。
  2. 添加所需的依赖。
  3. 创建数据访问层。
  4. 创建业务层。
  5. 创建控制器类。
  6. 测试应用。

示例:pom.xml文件中的依赖:

<dependencies>
    <!-- web依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
    <!-- data jpa依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-data-jpa</artifactid>
    </dependency>
    <!-- h2数据库依赖 -->
    <dependency>
        <groupid>com.h2database</groupid>
        <artifactid>h2</artifactid>
        <scope>runtime</scope>
    </dependency>
    <!-- apache poi依赖 -->
    <dependency>
        <groupid>org.apache.poi</groupid>
        <artifactid>poi</artifactid>
        <version>4.1.2</version>
    </dependency>
    <dependency>
        <groupid>org.apache.poi</groupid>
        <artifactid>poi-ooxml</artifactid>
        <version>4.1.2</version>
    </dependency>
    <!-- 测试依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-test</artifactid>
        <scope>test</scope>
    </dependency>
</dependencies>

application.properties文件中的配置:

# 服务器端口
server.port=8080
# 数据库连接信息
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.driver
spring.datasource.username=sa
spring.datasource.password=password
# jpa配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# h2数据库控制台
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

实体类:

import javax.persistence.*;

@entity
@table(name = "product")
public class product {
    @id
    @generatedvalue(strategy = generationtype.identity)
    private long id;
    private string productid;
    private string productname;
    private double price;
    private int sales;
    
    public product() {
    }
    
    public product(string productid, string productname, double price, int sales) {
        this.productid = productid;
        this.productname = productname;
        this.price = price;
        this.sales = sales;
    }
    
    // getter和setter方法
    public long getid() {
        return id;
    }
    
    public void setid(long id) {
        this.id = id;
    }
    
    public string getproductid() {
        return productid;
    }
    
    public void setproductid(string productid) {
        this.productid = productid;
    }
    
    public string getproductname() {
        return productname;
    }
    
    public void setproductname(string productname) {
        this.productname = productname;
    }
    
    public double getprice() {
        return price;
    }
    
    public void setprice(double price) {
        this.price = price;
    }
    
    public int getsales() {
        return sales;
    }
    
    public void setsales(int sales) {
        this.sales = sales;
    }
    
    @override
    public string tostring() {
        return "product{" +
                "id=" + id +
                ", productid='" + productid + '\'' +
                ", productname='" + productname + '\'' +
                ", price=" + price +
                ", sales=" + sales +
                '}';
    }
}

repository接口:

import org.springframework.data.jpa.repository.jparepository;
import org.springframework.stereotype.repository;

@repository
public interface productrepository extends jparepository<product, long> {
}

service类:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.xssfworkbook;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
import org.springframework.transaction.annotation.transactional;
import org.springframework.web.multipart.multipartfile;

import java.io.bytearrayoutputstream;
import java.io.ioexception;
import java.util.arraylist;
import java.util.iterator;
import java.util.list;

@service
public class productservice {
    @autowired
    private productrepository productrepository;
    
    @transactional
    public void importproducts(multipartfile file) throws ioexception {
        list<product> products = new arraylist<>();
        workbook workbook = new xssfworkbook(file.getinputstream());
        sheet sheet = workbook.getsheetat(0);
        iterator<row> iterator = sheet.iterator();
        
        if (iterator.hasnext()) {
            iterator.next(); // 跳过标题行
        }
        
        while (iterator.hasnext()) {
            row currentrow = iterator.next();
            product product = new product();
            product.setproductid(currentrow.getcell(0).getstringcellvalue());
            product.setproductname(currentrow.getcell(1).getstringcellvalue());
            product.setprice(currentrow.getcell(2).getnumericcellvalue());
            product.setsales((int) currentrow.getcell(3).getnumericcellvalue());
            products.add(product);
        }
        
        productrepository.saveall(products);
        workbook.close();
    }
    
    @transactional(readonly = true)
    public byte[] exportproducts() throws ioexception {
        list<product> products = productrepository.findall();
        workbook workbook = new xssfworkbook();
        sheet sheet = workbook.createsheet("products");
        row headerrow = sheet.createrow(0);
        
        cell headercell0 = headerrow.createcell(0);
        headercell0.setcellvalue("product id");
        
        cell headercell1 = headerrow.createcell(1);
        headercell1.setcellvalue("product name");
        
        cell headercell2 = headerrow.createcell(2);
        headercell2.setcellvalue("price");
        
        cell headercell3 = headerrow.createcell(3);
        headercell3.setcellvalue("sales");
        
        int rownum = 1;
        for (product product : products) {
            row row = sheet.createrow(rownum++);
            row.createcell(0).setcellvalue(product.getproductid());
            row.createcell(1).setcellvalue(product.getproductname());
            row.createcell(2).setcellvalue(product.getprice());
            row.createcell(3).setcellvalue(product.getsales());
        }
        
        for (int i = 0; i < 4; i++) {
            sheet.autosizecolumn(i);
        }
        
        bytearrayoutputstream outputstream = new bytearrayoutputstream();
        workbook.write(outputstream);
        workbook.close();
        
        return outputstream.tobytearray();
    }
    
    @transactional
    public product addproduct(product product) {
        return productrepository.save(product);
    }
    
    @transactional(readonly = true)
    public list<product> getallproducts() {
        return productrepository.findall();
    }
}

控制器类:

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.http.httpheaders;
import org.springframework.http.mediatype;
import org.springframework.http.responseentity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.multipartfile;

import java.io.ioexception;
import java.util.list;

@restcontroller
@requestmapping("/api/products")
public class productcontroller {
    @autowired
    private productservice productservice;
    
    @postmapping("/import")
    public responseentity<string> importproducts(@requestparam("file") multipartfile file) {
        try {
            productservice.importproducts(file);
            return responseentity.ok("数据导入成功");
        } catch (ioexception e) {
            e.printstacktrace();
            return responseentity.status(500).body("数据导入失败:" + e.getmessage());
        }
    }
    
    @getmapping("/export")
    public responseentity<byte[]> exportproducts() {
        try {
            byte[] bytes = productservice.exportproducts();
            httpheaders headers = new httpheaders();
            headers.setcontenttype(mediatype.parsemediatype("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            headers.setcontentdispositionformdata("attachment", "products.xlsx");
            headers.setcachecontrol("must-revalidate, post-check=0, pre-check=0");
            return responseentity.ok().headers(headers).body(bytes);
        } catch (ioexception e) {
            e.printstacktrace();
            return responseentity.status(500).body(null);
        }
    }
    
    @postmapping("/")
    public product addproduct(@requestbody product product) {
        return productservice.addproduct(product);
    }
    
    @getmapping("/")
    public list<product> getallproducts() {
        return productservice.getallproducts();
    }
}

应用启动类:

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;

@springbootapplication
public class productapplication {
    public static void main(string[] args) {
        springapplication.run(productapplication.class, args);
    }
    
    @autowired
    private productservice productservice;
    
    public void run(string... args) {
        // 初始化数据
        productservice.addproduct(new product("p001", "手机", 1000.0, 100));
        productservice.addproduct(new product("p002", "电脑", 5000.0, 50));
        productservice.addproduct(new product("p003", "电视", 3000.0, 80));
        productservice.addproduct(new product("p004", "手表", 500.0, 200));
        productservice.addproduct(new product("p005", "耳机", 300.0, 150));
    }
}

测试类:

import org.junit.jupiter.api.test;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.test.context.springboottest;
import org.springframework.boot.test.web.client.testresttemplate;
import org.springframework.boot.web.server.localserverport;
import org.springframework.http.httpentity;
import org.springframework.http.httpheaders;
import org.springframework.http.httpmethod;
import org.springframework.http.responseentity;
import org.springframework.util.linkedmultivaluemap;
import org.springframework.util.multivaluemap;
import org.springframework.web.multipart.multipartfile;
import org.springframework.web.multipart.commons.commonsmultipartfile;

import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstream;

import static org.assertj.core.api.assertions.assertthat;

@springboottest(webenvironment = springboottest.webenvironment.random_port)
class productapplicationtests {
    @localserverport
    private int port;
    
    @autowired
    private testresttemplate resttemplate;
    
    @test
    void contextloads() {
    }
    
    @test
    void testaddproduct() {
        product product = new product("p006", "平板", 2000.0, 70);
        product savedproduct = resttemplate.postforobject("http://localhost:" + port + "/api/products/", product, product.class);
        assertthat(savedproduct).isnotnull();
        assertthat(savedproduct.getproductid()).isequalto("p006");
    }
    
    @test
    void testgetallproducts() {
        list<product> products = resttemplate.getforobject("http://localhost:" + port + "/api/products/", list.class);
        assertthat(products).isnotnull();
        assertthat(products.size()).isgreaterthanorequalto(5);
    }
    
    @test
    void testimportproducts() throws ioexception {
        file file = new file("src/test/resources/products.xlsx");
        inputstream inputstream = new fileinputstream(file);
        multipartfile multipartfile = new commonsmultipartfile(inputstream);
        
        httpheaders headers = new httpheaders();
        headers.setcontenttype(mediatype.multipart_form_data);
        
        multivaluemap<string, object> body = new linkedmultivaluemap<>();
        body.add("file", multipartfile);
        
        httpentity<multivaluemap<string, object>> requestentity = new httpentity<>(body, headers);
        
        responseentity<string> response = resttemplate.exchange("http://localhost:" + port + "/api/products/import", httpmethod.post, requestentity, string.class);
        
        assertthat(response.getstatuscodevalue()).isequalto(200);
        assertthat(response.getbody()).contains("数据导入成功");
    }
    
    @test
    void testexportproducts() {
        responseentity<byte[]> response = resttemplate.getforentity("http://localhost:" + port + "/api/products/export", byte[].class);
        assertthat(response.getstatuscodevalue()).isequalto(200);
        assertthat(response.getbody()).isnotnull();
        assertthat(response.getbody().length).isgreaterthan(0);
    }
}

结论:集成apache poi的步骤包括创建spring boot项目、添加所需的依赖、创建数据访问层、创建业务层、创建控制器类、测试应用。

spring boot与报表生成的基本方法

spring boot与报表生成的基本方法包括使用apache poi、使用jasperreports、使用excel模板。

使用jasperreports

定义:使用jasperreports是指spring boot与报表生成集成的基本方法之一。

作用

  • 实现报表生成。
  • 提高应用程序的性能。

示例:pom.xml文件中的依赖:

<dependencies>
    <!-- web依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
    <!-- data jpa依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-data-jpa</artifactid>
    </dependency>
    <!-- h2数据库依赖 -->
    <dependency>
        <groupid>com.h2database</groupid>
        <artifactid>h2</artifactid>
        <scope>runtime</scope>
    </dependency>
    <!-- jasperreports依赖 -->
    <dependency>
        <groupid>net.sf.jasperreports</groupid>
        <artifactid>jasperreports</artifactid>
        <version>6.17.0</version>
    </dependency>
    <dependency>
        <groupid>net.sf.jasperreports</groupid>
        <artifactid>jasperreports-fonts</artifactid>
        <version>6.17.0</version>
    </dependency>
    <!-- 测试依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-test</artifactid>
        <scope>test</scope>
    </dependency>
</dependencies>

service类:

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.jrbeancollectiondatasource;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
import org.springframework.transaction.annotation.transactional;

import java.io.bytearrayoutputstream;
import java.io.inputstream;
import java.util.hashmap;
import java.util.list;
import java.util.map;

@service
public class reportservice {
    @autowired
    private productrepository productrepository;
    
    @transactional(readonly = true)
    public byte[] generateproductreport() throws jrexception {
        list<product> products = productrepository.findall();
        
        // 加载jasper模板
        inputstream templatestream = getclass().getresourceasstream("/reports/product-report.jasper");
        jasperreport jasperreport = (jasperreport) jrloader.loadobject(templatestream);
        
        // 设置参数
        map<string, object> parameters = new hashmap<>();
        parameters.put("title", "产品销售报表");
        
        // 设置数据源
        jrbeancollectiondatasource datasource = new jrbeancollectiondatasource(products);
        
        // 生成报表
        jasperprint jasperprint = jasperfillmanager.fillreport(jasperreport, parameters, datasource);
        
        // 导出报表为pdf
        bytearrayoutputstream outputstream = new bytearrayoutputstream();
        jasperexportmanager.exportreporttopdfstream(jasperprint, outputstream);
        
        return outputstream.tobytearray();
    }
}

控制器类:

import net.sf.jasperreports.engine.jrexception;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.http.httpheaders;
import org.springframework.http.mediatype;
import org.springframework.http.responseentity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.multipartfile;

import java.io.ioexception;
import java.util.list;

@restcontroller
@requestmapping("/api/products")
public class productcontroller {
    @autowired
    private productservice productservice;
    
    @autowired
    private reportservice reportservice;
    
    @getmapping("/report")
    public responseentity<byte[]> generateproductreport() {
        try {
            byte[] bytes = reportservice.generateproductreport();
            httpheaders headers = new httpheaders();
            headers.setcontenttype(mediatype.parsemediatype("application/pdf"));
            headers.setcontentdispositionformdata("attachment", "product-report.pdf");
            headers.setcachecontrol("must-revalidate, post-check=0, pre-check=0");
            return responseentity.ok().headers(headers).body(bytes);
        } catch (jrexception e) {
            e.printstacktrace();
            return responseentity.status(500).body(null);
        }
    }
    
    @postmapping("/import")
    public responseentity<string> importproducts(@requestparam("file") multipartfile file) {
        try {
            productservice.importproducts(file);
            return responseentity.ok("数据导入成功");
        } catch (ioexception e) {
            e.printstacktrace();
            return responseentity.status(500).body("数据导入失败:" + e.getmessage());
        }
    }
    
    @getmapping("/export")
    public responseentity<byte[]> exportproducts() {
        try {
            byte[] bytes = productservice.exportproducts();
            httpheaders headers = new httpheaders();
            headers.setcontenttype(mediatype.parsemediatype("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            headers.setcontentdispositionformdata("attachment", "products.xlsx");
            headers.setcachecontrol("must-revalidate, post-check=0, pre-check=0");
            return responseentity.ok().headers(headers).body(bytes);
        } catch (ioexception e) {
            e.printstacktrace();
            return responseentity.status(500).body(null);
        }
    }
    
    @postmapping("/")
    public product addproduct(@requestbody product product) {
        return productservice.addproduct(product);
    }
    
    @getmapping("/")
    public list<product> getallproducts() {
        return productservice.getallproducts();
    }
}

测试类:

import org.junit.jupiter.api.test;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.test.context.springboottest;
import org.springframework.boot.test.web.client.testresttemplate;
import org.springframework.boot.web.server.localserverport;
import org.springframework.http.httpentity;
import org.springframework.http.httpheaders;
import org.springframework.http.httpmethod;
import org.springframework.http.responseentity;
import org.springframework.util.linkedmultivaluemap;
import org.springframework.util.multivaluemap;
import org.springframework.web.multipart.multipartfile;
import org.springframework.web.multipart.commons.commonsmultipartfile;

import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstream;

import static org.assertj.core.api.assertions.assertthat;

@springboottest(webenvironment = springboottest.webenvironment.random_port)
class productapplicationtests {
    @localserverport
    private int port;
    
    @autowired
    private testresttemplate resttemplate;
    
    @test
    void contextloads() {
    }
    
    @test
    void testaddproduct() {
        product product = new product("p006", "平板", 2000.0, 70);
        product savedproduct = resttemplate.postforobject("http://localhost:" + port + "/api/products/", product, product.class);
        assertthat(savedproduct).isnotnull();
        assertthat(savedproduct.getproductid()).isequalto("p006");
    }
    
    @test
    void testgetallproducts() {
        list<product> products = resttemplate.getforobject("http://localhost:" + port + "/api/products/", list.class);
        assertthat(products).isnotnull();
        assertthat(products.size()).isgreaterthanorequalto(5);
    }
    
    @test
    void testimportproducts() throws ioexception {
        file file = new file("src/test/resources/products.xlsx");
        inputstream inputstream = new fileinputstream(file);
        multipartfile multipartfile = new commonsmultipartfile(inputstream);
        
        httpheaders headers = new httpheaders();
        headers.setcontenttype(mediatype.multipart_form_data);
        
        multivaluemap<string, object> body = new linkedmultivaluemap<>();
        body.add("file", multipartfile);
        
        httpentity<multivaluemap<string, object>> requestentity = new httpentity<>(body, headers);
        
        responseentity<string> response = resttemplate.exchange("http://localhost:" + port + "/api/products/import", httpmethod.post, requestentity, string.class);
        
        assertthat(response.getstatuscodevalue()).isequalto(200);
        assertthat(response.getbody()).contains("数据导入成功");
    }
    
    @test
    void testexportproducts() {
        responseentity<byte[]> response = resttemplate.getforentity("http://localhost:" + port + "/api/products/export", byte[].class);
        assertthat(response.getstatuscodevalue()).isequalto(200);
        assertthat(response.getbody()).isnotnull();
        assertthat(response.getbody().length).isgreaterthan(0);
    }
    
    @test
    void testgenerateproductreport() {
        responseentity<byte[]> response = resttemplate.getforentity("http://localhost:" + port + "/api/products/report", byte[].class);
        assertthat(response.getstatuscodevalue()).isequalto(200);
        assertthat(response.getbody()).isnotnull();
        assertthat(response.getbody().length).isgreaterthan(0);
    }
}

结论:使用jasperreports是指spring boot与报表生成集成的基本方法之一,作用是实现报表生成、提高应用程序的性能。

spring boot的实际应用场景

在实际开发中,spring boot数据导入导出与报表生成的应用场景非常广泛,如:

  • 实现产品信息的导入导出。
  • 实现用户信息的导入导出。
  • 实现订单信息的导入导出。
  • 实现产品销售报表的生成。

示例

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;

@springbootapplication
public class productapplication {
    public static void main(string[] args) {
        springapplication.run(productapplication.class, args);
    }
    
    @autowired
    private productservice productservice;
    
    public void run(string... args) {
        // 初始化数据
        productservice.addproduct(new product("p001", "手机", 1000.0, 100));
        productservice.addproduct(new product("p002", "电脑", 5000.0, 50));
        productservice.addproduct(new product("p003", "电视", 3000.0, 80));
        productservice.addproduct(new product("p004", "手表", 500.0, 200));
        productservice.addproduct(new product("p005", "耳机", 300.0, 150));
    }
}

@service
class productservice {
    @autowired
    private productrepository productrepository;
    
    @transactional
    public void importproducts(multipartfile file) throws ioexception {
        list<product> products = new arraylist<>();
        workbook workbook = new xssfworkbook(file.getinputstream());
        sheet sheet = workbook.getsheetat(0);
        iterator<row> iterator = sheet.iterator();
        
        if (iterator.hasnext()) {
            iterator.next(); // 跳过标题行
        }
        
        while (iterator.hasnext()) {
            row currentrow = iterator.next();
            product product = new product();
            product.setproductid(currentrow.getcell(0).getstringcellvalue());
            product.setproductname(currentrow.getcell(1).getstringcellvalue());
            product.setprice(currentrow.getcell(2).getnumericcellvalue());
            product.setsales((int) currentrow.getcell(3).getnumericcellvalue());
            products.add(product);
        }
        
        productrepository.saveall(products);
        workbook.close();
    }
    
    @transactional(readonly = true)
    public byte[] exportproducts() throws ioexception {
        list<product> products = productrepository.findall();
        workbook workbook = new xssfworkbook();
        sheet sheet = workbook.createsheet("products");
        row headerrow = sheet.createrow(0);
        
        cell headercell0 = headerrow.createcell(0);
        headercell0.setcellvalue("product id");
        
        cell headercell1 = headerrow.createcell(1);
        headercell1.setcellvalue("product name");
        
        cell headercell2 = headerrow.createcell(2);
        headercell2.setcellvalue("price");
        
        cell headercell3 = headerrow.createcell(3);
        headercell3.setcellvalue("sales");
        
        int rownum = 1;
        for (product product : products) {
            row row = sheet.createrow(rownum++);
            row.createcell(0).setcellvalue(product.getproductid());
            row.createcell(1).setcellvalue(product.getproductname());
            row.createcell(2).setcellvalue(product.getprice());
            row.createcell(3).setcellvalue(product.getsales());
        }
        
        for (int i = 0; i < 4; i++) {
            sheet.autosizecolumn(i);
        }
        
        bytearrayoutputstream outputstream = new bytearrayoutputstream();
        workbook.write(outputstream);
        workbook.close();
        
        return outputstream.tobytearray();
    }
    
    @transactional
    public product addproduct(product product) {
        return productrepository.save(product);
    }
    
    @transactional(readonly = true)
    public list<product> getallproducts() {
        return productrepository.findall();
    }
}

@restcontroller
@requestmapping("/api/products")
class productcontroller {
    @autowired
    private productservice productservice;
    
    @autowired
    private reportservice reportservice;
    
    @getmapping("/report")
    public responseentity<byte[]> generateproductreport() {
        try {
            byte[] bytes = reportservice.generateproductreport();
            httpheaders headers = new httpheaders();
            headers.setcontenttype(mediatype.parsemediatype("application/pdf"));
            headers.setcontentdispositionformdata("attachment", "product-report.pdf");
            headers.setcachecontrol("must-revalidate, post-check=0, pre-check=0");
            return responseentity.ok().headers(headers).body(bytes);
        } catch (jrexception e) {
            e.printstacktrace();
            return responseentity.status(500).body(null);
        }
    }
    
    @postmapping("/import")
    public responseentity<string> importproducts(@requestparam("file") multipartfile file) {
        try {
            productservice.importproducts(file);
            return responseentity.ok("数据导入成功");
        } catch (ioexception e) {
            e.printstacktrace();
            return responseentity.status(500).body("数据导入失败:" + e.getmessage());
        }
    }
    
    @getmapping("/export")
    public responseentity<byte[]> exportproducts() {
        try {
            byte[] bytes = productservice.exportproducts();
            httpheaders headers = new httpheaders();
            headers.setcontenttype(mediatype.parsemediatype("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            headers.setcontentdispositionformdata("attachment", "products.xlsx");
            headers.setcachecontrol("must-revalidate, post-check=0, pre-check=0");
            return responseentity.ok().headers(headers).body(bytes);
        } catch (ioexception e) {
            e.printstacktrace();
            return responseentity.status(500).body(null);
        }
    }
    
    @postmapping("/")
    public product addproduct(@requestbody product product) {
        return productservice.addproduct(product);
    }
    
    @getmapping("/")
    public list<product> getallproducts() {
        return productservice.getallproducts();
    }
}

// 测试类
@springboottest(webenvironment = springboottest.webenvironment.random_port)
class productapplicationtests {
    @localserverport
    private int port;
    
    @autowired
    private testresttemplate resttemplate;
    
    @test
    void contextloads() {
    }
    
    @test
    void testaddproduct() {
        product product = new product("p006", "平板", 2000.0, 70);
        product savedproduct = resttemplate.postforobject("http://localhost:" + port + "/api/products/", product, product.class);
        assertthat(savedproduct).isnotnull();
        assertthat(savedproduct.getproductid()).isequalto("p006");
    }
    
    @test
    void testgetallproducts() {
        list<product> products = resttemplate.getforobject("http://localhost:" + port + "/api/products/", list.class);
        assertthat(products).isnotnull();
        assertthat(products.size()).isgreaterthanorequalto(5);
    }
    
    @test
    void testimportproducts() throws ioexception {
        file file = new file("src/test/resources/products.xlsx");
        inputstream inputstream = new fileinputstream(file);
        multipartfile multipartfile = new commonsmultipartfile(inputstream);
        
        httpheaders headers = new httpheaders();
        headers.setcontenttype(mediatype.multipart_form_data);
        
        multivaluemap<string, object> body = new linkedmultivaluemap<>();
        body.add("file", multipartfile);
        
        httpentity<multivaluemap<string, object>> requestentity = new httpentity<>(body, headers);
        
        responseentity<string> response = resttemplate.exchange("http://localhost:" + port + "/api/products/import", httpmethod.post, requestentity, string.class);
        
        assertthat(response.getstatuscodevalue()).isequalto(200);
        assertthat(response.getbody()).contains("数据导入成功");
    }
    
    @test
    void testexportproducts() {
        responseentity<byte[]> response = resttemplate.getforentity("http://localhost:" + port + "/api/products/export", byte[].class);
        assertthat(response.getstatuscodevalue()).isequalto(200);
        assertthat(response.getbody()).isnotnull();
        assertthat(response.getbody().length).isgreaterthan(0);
    }
    
    @test
    void testgenerateproductreport() {
        responseentity<byte[]> response = resttemplate.getforentity("http://localhost:" + port + "/api/products/report", byte[].class);
        assertthat(response.getstatuscodevalue()).isequalto(200);
        assertthat(response.getbody()).isnotnull();
        assertthat(response.getbody().length).isgreaterthan(0);
    }
}

输出结果

访问http://localhost:8080/api/products/report:下载产品销售报表(pdf格式)。
访问http://localhost:8080/api/products/import:上传产品信息excel文件,导入数据。
访问http://localhost:8080/api/products/export:下载产品信息excel文件。

结论:在实际开发中,spring boot数据导入导出与报表生成的应用场景非常广泛,需要根据实际问题选择合适的导入导出格式和报表生成工具。

总结

本章我们学习了spring boot数据导入导出与报表生成,包括数据导入导出的定义与特点、spring boot与数据导入导出的集成、spring boot与数据导入导出的配置、spring boot与报表生成的基本方法、spring boot的实际应用场景,学会了在实际开发中处理数据导入导出与报表生成问题。其中,数据导入导出的定义与特点、spring boot与数据导入导出的集成、spring boot与数据导入导出的配置、spring boot与报表生成的基本方法、spring boot的实际应用场景是本章的重点内容。

以上就是springboot实现数据导入导出与报表生成的完整教程的详细内容,更多关于springboot数据导入导出的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com