4
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.

SuperCSVでBeanのリストを和名ヘッダーをつけてCSV出力

Last updated at Posted at 2015-06-26

javaのCSVライブラリのひとつ、Super CSVの使い方の紹介
http://super-csv.github.io/super-csv/index.html

Beanのリストを、表示用の名称のヘッダーをつけてCSV出力

例えば、次のようなBeanのリストを、コメントにある表示名のヘッダーで出力したいとします。

 class User {
           /**
            * ユーザID
            */   
           private String id;
   
           /**
            * ユーザ名
            */ 
           private String name;

           /**
            * 削除フラグ
            */
           private boolean deleted;

           /* 中略 */ 
        }

表示用のヘッダーと、プロパティ名をそれぞれ配列として用意して、下記のようにすればよいです。
ポイントはwriteHeaderとwriteでヘッダーを使い分けるところです。

       
        //表示用のヘッダー
        String[] viewHeader = new {"ユーザID","ユーザ名","削除フラグ"}

        //プロパティ名の配列をヘッダーと同じ順番で作成
        String[] header = new {"id","name", "deleted"}   

        //Bean
        List<User> allUsers = User.find.all();

        ICsvBeanWriter beanWriter = null;
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try {
            //文字コードを指定
            fos = new FileOutputStream(csvFile);
            osw = new OutputStreamWriter(fos, "Shift_JIS");
       
       //エクセルでも開ける形式のライター
            beanWriter = new CsvBeanWriter(osw, CsvPreference.EXCEL_PREFERENCE);

            //ヘッダーを書き込み
            beanWriter.writeHeader(viewHeader);

            for(Object bean: beans) {
                //Beanの内容を書き込み
                beanWriter.write(bean, header);
            }
        } catch(IOException e) {
            Logger.error("writing beans failed.", e);
        } finally {
            if (beanWriter != null) {
                beanWriter.close();
            }
            if (osw != null) {
                osw.close();
            }
            if (fos != null) {
                fos.close();
            }
        }

文字コードも指定しているので、長くなっていますが、CSVの大体のことを決められます。

実践では、プロパティ名と表示名の対応関係は設定ファイルに持たせて、そこからviewHeaderを作る、などという形をとりました。

Super CSVにCellProcessorというものがあり、それで出力形式を色々コントロールできます。
例えば日付はyyyy/MM/ddにしたり、booleanを0 or 1にしたりなどができます。
http://super-csv.github.io/super-csv/cell_processors.html

4
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
4
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?