8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Java]CSVの特定カラムだけにクオートをつける

Last updated at Posted at 2017-11-20

背景

  • SpringでCSV出力機能を作ろうとしている
  • ベースはこの記事を真似すればすぐにできた

課題

  • CSVの特定のカラムだけにクオートをつけたい
  • 少し調べただけだとString型のカラム全てクオートをつけるかつけないかしかできなかった

対応策

  • String型は全てクオートをつける設定にする
  • クオートをつけたくないカラムに@JsonRawValueをつける

サンプル

SampleController.java
@RestController
public class SampleController {
    @GetMapping(value="/sample.csv", produces="text/csv;charset=utf-8;Content-Disposition:attachment")
    public String csv() throws JsonProcessingException {
        List<UserBean> rows = new ArrayList<UserBean>() {
            {
                add(new UserBean("ozaki", "runners", 27));
            }
        };
        CsvMapper mapper = new CsvMapper();
        // withHeaderをつけると一行目にヘッダーがつく
        CsvSchema schema = mapper.schemaFor(UserBean.class).withHeader();
        // ALWAYS_QUOTE_STRINGSとするとString型のカラムはクオートをつけるよってことになる
        mapper.configure(CsvGenerator.Feature.ALWAYS_QUOTE_STRINGS, true);
        return mapper.writer(schema).writeValueAsString(rows);
    }
}
UserBean.java
// CSVのカラムの順番をセット
@JsonPropertyOrder({"name", "team", "age"})
public class UserBean {
    private String name;
    // JsonRawValueがあるとクオートがつかない
    @JsonRawValue
    private String team;
    private Integer age;

    public UserBean(String name, String team, Integer age) {
        this.name = name;
        this.team = team;
        this.age = age;
    }

    /* setter/getter */
sample.csv
"name","team","age"
"ozaki",runners,27
8
4
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
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?