【问题标题】:How to get selective columns in Export Csv in Spring boot如何在 Spring Boot 中的 Export Csv 中获取选择性列
【发布时间】:2021-11-30 23:02:18
【问题描述】:

我是 Spring Boot 新手,我正在创建一个 Spring Boot 应用程序来从从数据库中获取的数据生成 csv 文件。我正在使用 h2 数据库并希望从我的实体 ID 中获取选择性列,数量

实体类:

package com.reports.entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity(name="reportDetails")
@Table(name = "reports")
public class Report {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private long id;
    @Column(name="name")
    private String name;
    @Column(name="email")
    private String email;
    @Column(name="amount")
    private int amount;
    
    public Report() {
        super();
    }
    public Report(int id, String name, String email, int amount) {
        super();
        this.id = id;
        this.name = name;
        this.email = email;
        this.amount = amount;
    }
    public long getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public int getAmount() {
        return amount;
    }
    public void setAmount(int amount) {
        this.amount = amount;
    }
    
    
    }

主类:

package com.reports;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.reports.entities.Report;
import com.reports.repository.ReportsRepository;

@SpringBootApplication
public class ExportCsvApplication implements CommandLineRunner {
    @Autowired
    ReportsRepository reportsRepository;

    public static void main(String[] args) {
        SpringApplication.run(ExportCsvApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        List<Report> reports = new ArrayList<>();

        // create dummy employees
        reports.add(new Report(1,"roy","roy@123.com",2500));
        reports.add(new Report(2,"joy","joy@123.com",2500));
        reports.add(new Report(3,"soy","soy@123.com",2500));
        reports.add(new Report(4,"moy","moy@123.com",2500));
        reports.add(new Report(5,"noy","noy@123.com",2500));
        
        reportsRepository.saveAll(reports);
    }

}

存储库:

package com.reports.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.reports.entities.IReport;
import com.reports.entities.Report;

@Repository("reportsRepository")
public interface ReportsRepository extends JpaRepository<Report,Long>{

}

服务类:

package com.reports.services;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.reports.entities.IReport;
import com.reports.entities.Report;
import com.reports.repository.ReportsRepository;
@Transactional
@Service
public class ReportsService {
    @Autowired
   ReportsRepository reportsRepository;

    public List<Report> fetchAll() {
        return (List<Report>) reportsRepository.findAll();
       

    }

    
}

控制器:

package com.reports.controllers;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.reports.entities.Report;
import com.reports.services.ReportsService;

@RestController
public class ReportsController {

    @Autowired
    ReportsService reportsService;
    @GetMapping("/export-report")
    public void exportCSV(HttpServletResponse response) throws Exception {

        // set file name and content type
        String filename = "details.csv";

        response.setContentType("text/csv");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, 
                   "attachment; filename=\"" + filename + "\"");

        // create a csv writer
        StatefulBeanToCsv<Report> writer = new StatefulBeanToCsvBuilder<Report>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false).build();

        // write all employees to csv file
        writer.write(reportsService.fetchAll());

    }
    
    
    
   
}

我想知道合并它的最佳方法是什么,我尝试查询但遇到错误。请告诉我如何完成此操作

【问题讨论】:

    标签: java spring-boot spring-data-jpa opencsv export-csv


    【解决方案1】:

    这更多地与 opencsv 库有关,而不是 SpringSpring Boot 本身。

    在构造StatefullBeanToCsvBuilder 时,您应该使用withIgonreField 构建器属性来指示最终的StatefullBeanToCsv 对于哪些类型要忽略哪些字段。

    假设您只想要Report 实体中的idamount 字段,您可以按如下方式实现:

    @RestController
    public class ReportsController {
    
        @Autowired
        ReportsService reportsService;
    
        @GetMapping("/export-report")
        public void exportCSV(HttpServletResponse response) throws Exception {
    
            // set file name and content type
            String filename = "details.csv";
            response.setContentType("text/csv");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, 
                       "attachment; filename=\"" + filename + "\"");
    
            // Configure the CSV writer builder
            StatefulBeanToCsvBuilder<Report> builder = new StatefulBeanToCsvBuilder<Report>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false);
    
            // Ignore any field except the `id` and `amount` ones
            Arrays.stream(Report.class.getDeclaredFields())
                    .filter(field -> !("id".equals(field.getName()) || "amount".equals(field.getName())))
                    .forEach(field -> builder.withIgnoreField(Report.class, field));
    
            // create a csv writer
            StatefulBeanToCsv<Report> writer = builder.build();
    
            // write all employees to csv file
            writer.write(reportsService.fetchAll());
    
        }  
    }
    

    【讨论】:

    • 使用此方法出现此错误:- 对于 StatefulBeanToCsvBuilder 类型,未定义方法 withIgnoreField(Class, Field)
    • 您使用的是哪个opencsv 版本?
    • 我正在使用版本:4.5
    • 升级到 5.x 对您来说是一个不错的选择吗?
    • 是的,应该不是问题,最好使用哪个版本?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2020-02-04
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2015-09-22
    相关资源
    最近更新 更多