Last active
September 14, 2018 08:46
-
-
Save skysan87/275700e208042c9cffeb47cfd5da56de to your computer and use it in GitHub Desktop.
[C#] 改行文字、カンマを含んだCSVの変換
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private readonly List<char> newlineChar = Environment.NewLine.ToCharArray().ToList(); | |
/// <summary> | |
/// CSVファイルを読込、Listに変換する。 | |
/// | |
/// 改行文字やカンマを含む値は | |
/// ダブルクォーテーションで囲んであるものとする。 | |
/// </summary> | |
/// <param name="filepath">CSVファイルのパス</param> | |
/// <returns></returns> | |
private List<string[]> LoadCSV(string filepath) | |
{ | |
List<string> header = new List<string>(); | |
List<string[]> records = new List<string[]>(); | |
const char delimiter = ','; | |
const char stringDelimiter = '"'; | |
using(var stream = new StreamReader(filepath, Encoding.GetEncoding("Shift_JIS"))) | |
{ | |
//ヘッダーに改行は含まれないものとする | |
header.AddRange(stream.ReadLine().Split(',')); | |
records.Add(header.ToArray()); | |
var line = new List<string>(); | |
var builer = new StringBuilder(); | |
int count = 0; | |
char readChar; | |
bool betweenQuotes = false; | |
bool lastColumn = false; | |
var newlineCharHolder = new List<char>(); | |
while (stream.Peek() >= 0) | |
{ | |
readChar = (char)stream.Read(); | |
// ダブルクォーテーション | |
if (stringDelimiter == readChar) | |
{ | |
if (betweenQuotes == false) | |
{ | |
betweenQuotes = true; | |
} | |
else | |
{ | |
betweenQuotes = false; | |
} | |
} | |
// 改行文字 | |
if (newlineChar.Contains(readChar) && lastColumn && betweenQuotes == false) | |
{ | |
newlineCharHolder.Add(readChar); | |
//すべての改行文字を取得してから次の行に行く | |
if (new String(newlineCharHolder.ToArray()).Equals(Environment.NewLine)) | |
{ | |
//最後のカラム | |
line.Add(builer.ToString()); | |
builer.Clear(); | |
records.Add(line.ToArray()); | |
// 次の行へ | |
line.Clear(); | |
builer.Clear(); | |
count = 0; | |
lastColumn = false; | |
newlineCharHolder.Clear(); | |
} | |
continue; | |
} | |
// カンマ | |
if (delimiter == readChar && betweenQuotes == false) | |
{ | |
line.Add(builer.ToString()); | |
builer.Clear(); | |
count++; | |
if (count == header.Count - 1) | |
{ | |
lastColumn = true; | |
} | |
} | |
else | |
{ | |
builer.Append(readChar); | |
} | |
} | |
//最後行の末尾に改行がない場合 | |
if (line.Count > 0) | |
{ | |
//最後のカラム | |
line.Add(builer.ToString()); | |
records.Add(line.ToArray()); | |
} | |
} | |
return records; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment