LoginSignup
11
6

More than 5 years have passed since last update.

ElixirでExcelファイルを読み込む

Posted at

Elixirの練習にと、Excelの特定のセルの値からCSVを吐いてみた。
もとのExcelのファイルレイアウトは以下の感じ。
あえて、空欄があったり、文字にスペースが含まれていたりするので、良い題材。

Excel読み込む為に、Excelion というライブラリを使用した。

入力用Excelファイル

スクリーンショット 2017-07-05 22.20.06.png

何を処理しているかは、ソース内にコメントで説明。

convert_ex_csv.ex

defmodule ExcelSample do
    def convert do
        sheet_no = 0
        result = "roster.xlsx"  #=> 入力Excelファイル名
          |> Excelion.parse(sheet_no, 1)  # ExcelionでExcelファイル読み込み
          |> elem(1)                      # 戻り値の要素1番目を取得
          |> Enum.map(&([Enum.at(&1,2), Enum.at(&1,7)]))  # Cell[C]列と[H]列を指定
          |> Enum.filter(&(Enum.at(&1,0) != ""))  # 空欄行を排除
          |> Enum.filter(&(Regex.run ~r{[0-9]}, Enum.at(&1,0)))  # ヘッダ行を排除(背番号のみ)
          |> Enum.map(fn([no, name])->[no, String.split(name)] end) # Cellデータのスペース除去
          |> Enum.map(fn([no, [last_name, first_name]]) -> "\"#{no}\",\"#{last_name}\",\"#{first_name}\"\n" end)   # CSV整形

        File.write("roster.csv", result)  # ファイル出力
    end
end

吐かれたCSVは下記。

出力CSV

スクリーンショット 2017-07-05 22.23.01.png

時間が掛かったが、慣れてくると結構楽しい。

11
6
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
11
6