LoginSignup
19
28

More than 5 years have passed since last update.

【Java】CSVダウンロード機能の実装

Posted at

[例]DBに登録されている全ての顧客情報を取得し、CSVで出力したい

JSP

sample.jsp
<button type="button" onclick="location.href='${pageContext.request.contextPath}/csvDownload'">
     ユーザー情報一括ダウンロード(csv)</button>

Controller

Controller.java
    /**
     * ユーザー情報csv形式でダウンロードする
     */
    @RequestMapping("csvDownload")
    public void csvDownload(HttpServletResponse response) {

        //文字コードと出力するCSVファイル名を設定
        response.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE + ";charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"test.csv\"");

        //try-with-resources文を使うことでclose処理を自動化
        try (PrintWriter pw = response.getWriter()) {
            List<User> all_users = service.findAll();
            for (int i = 0; i < all_users.size(); i++) {
                long id = all_users.get(i).getId();
                String name = all_users.get(i).getName();
                String email = all_users.get(i).getEmail();
                String password = all_users.get(i).getPassword();
                String address = all_users.get(i).getAddress();
                String telephone = all_users.get(i).getTelephone();

                //CSVファイル内部に記載する形式で文字列を設定
                String outputString = id + "," + name + "," + email + "," + password + "," + address + "," + telephone
                         + "\r\n";

                //CSVファイルに書き込み
                pw.print(outputString);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
19
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
28