Spring Boot でCSVダウンロード

データが少ない時

データが多くてメモリ不足になりそうなら、データが多い時の方法を検討。
それでもだめならバックグラウンドでcsvファイルを生成しておいて、あとでDLさせるとか検討。

    @RequestMapping(value = "csvdownload", method = RequestMethod.GET)
    public ResponseEntity<byte[]> download() throws IOException {
        HttpHeaders header = new HttpHeaders();
        header.add("Content-Type", "text/csv; charset=shift_jis");
        header.setContentDispositionFormData("filename", "sample.csv");
        String csv = "\"data1\",\"data2\"";
        return new ResponseEntity<>(csv.getBytes("shift_jis"), header, HttpStatus.OK);
    }

データが多い時

出力したいデータを全部取得するとメモリが足りなくなるケースがあるはずなので、順次取得しながら出力する。

    @RequestMapping(value = "csvdownload", method=RequestMethod.GET)
    public void csvdownload(HttpServletResponse response) {
        response.addHeader("Content-Disposition", "attachment; filename=\"sample.csv\"");
        response.setContentType("text/csv; charset=shift_jis");
        try (ServletOutputStream out = response.getOutputStream()) {
            for (int i = 0; i < 10000000; i++) {
                // ここから
                String csv = "\"data1\",\"data2\"";
                out.write(csv.getBytes("shift_jis"));
                // ここまでをデータ取得しながらデータ出力する
            }
            out.flush();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

CAPTCHA