Springboot集成univocity-parsers下载csv文件

贾建茗
2023-12-01

说明

springboot下载csv参考:https://blog.csdn.net/sndayYU/article/details/119410446
下面工程以上面的为基础

代码

pom.xml和entity、mapper定义

<!-- csv工具 -->
        <dependency>
            <groupId>com.univocity</groupId>
            <artifactId>univocity-parsers</artifactId>
            <version>2.8.4</version>
        </dependency>
@Data
public class DownloadVo {
    @Parsed(field = "文章id")
    private Long id;
    @Parsed(field = "文章标题")
    private String title;
    @Parsed(field = "内容类型")
    private String contentType;
}
@Mapper
public interface DownloadMapper {
    @ResultType(DownloadVo.class)
    @Select("select id, title, content_type contentType " +
            " from dev_download with(nolock) ")
    void getAllDownloadVos(ResultHandler<DownloadVo> resultHandler);
}

service

@Component
public class CsvService {
    @Autowired
    private DownloadMapper downloadMapper;

    private void setHeader(HttpServletResponse response, String filename) throws Exception {
        response.setContentType("application/csv;charset=gb18030");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename + ".csv", "UTF-8"));
    }

    /************************* 使用mybatis的ResultHandler进行下载 *****************************/
    public void utilResultHandlerToCsv(HttpServletResponse response) throws Exception {
        // header
        response.setContentType("application/csv;charset=gb18030");
        response.setHeader("Content-Disposition", "attachment; filename="
                + URLEncoder.encode("utilResultHandlerToCsv" + ".csv", "UTF-8"));
        // csvWriter
        CsvWriterSettings settings = new CsvWriterSettings();
        settings.setRowWriterProcessor(new BeanWriterProcessor<>(DownloadVo.class));
        CsvWriter csvWriter = new CsvWriter(response.getWriter(), settings);
        // header
        csvWriter.writeHeaders();
        // data
        DownloadResultHandler handler = new DownloadResultHandler(csvWriter);
        downloadMapper.getAllDownloadVos(handler);

        // 刷新缓存
        csvWriter.flush();
    }
    public static class DownloadResultHandler implements ResultHandler<DownloadVo> {
        private CsvWriter writer;

        public DownloadResultHandler(CsvWriter writer) {
            this.writer = writer;
        }

        @Override
        public void handleResult(ResultContext<? extends DownloadVo> resultContext) {
            writer.processRecord(resultContext.getResultObject());
        }
    }
}

controller

@RestController
public class CsvController {
    @Autowired
    private CsvService csvService;
    @GetMapping("/csv/download1")
    public void download1(HttpServletResponse response) throws Exception {
        long time = System.currentTimeMillis();
        csvService.utilResultHandlerToCsv(response);
        System.out.println("utilResultHandlerToCsv time = " + (System.currentTimeMillis() - time));
    }
}

试验

访问http://localhost:8080/csv/download1,可正常下载csv

其它

可整理为一个工具类

public class CsvUtils {

    public static void writeToResponse(HttpServletResponse response, String filename, List data) throws IOException {
        if (CollectionUtils.isEmpty(data)) {
            return;
        }
        // header
        response.setContentType("application/csv;charset=gb18030");
        response.setHeader("Content-Disposition", "attachment; filename="
                + URLEncoder.encode(filename + ".csv", "UTF-8"));
        // csvWriter
        CsvWriterSettings settings = new CsvWriterSettings();
        settings.setRowWriterProcessor(new BeanWriterProcessor<>(data.get(0).getClass()));
        CsvWriter csvWriter = new CsvWriter(response.getWriter(), settings);
        // header
        csvWriter.writeHeaders();
        // data
        csvWriter.writeRecords(data);
        csvWriter.flush();
    }
}
 类似资料: