문제
문자열을 csv 형식에서 string[] 또는 목록으로 변환하는 쉬운 방법이 있습니까?
데이터에 쉼표가 없음을 보장할 수 있습니다.
해결책
string[] splitString = origString.Split(',');
(원래 답변자가 추가하지 않은 다음 설명) 이 답변은 데이터에 쉼표가 없음이 보장되는 특정 사례를 다룬다는 점을 명심하세요.
다른 팁
String.Split은 잘리지 않지만 Regex.Split은 그럴 수 있습니다. 다음을 시도해 보세요.
using System.Text.RegularExpressions;
string[] line;
line = Regex.Split( input, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
여기서 '입력'은 CSV 라인입니다.이는 따옴표로 묶인 구분 기호를 처리하고 줄의 각 필드를 나타내는 문자열 배열을 반환해야 합니다.
강력한 CSV 처리를 원한다면 다음을 확인하세요. FileHelpers
노력하다:
Regex rex = new Regex(",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))");
string[] values = rex.Split( csvLine );
원천: http://weblogs.asp.net/prieck/archive/2004/01/16/59457.aspx
다음과 함께 Microsoft.VisualBasic 어셈블리를 사용하는 방법을 살펴볼 수 있습니다.
Microsoft.VisualBasic.FileIO.TextFieldParser
따옴표가 포함된 CSV(또는 구분 기호)를 처리합니다.최근에 꽤 편리하다는 것을 알았습니다.
쉼표가 포함된 인용 요소를 설명하려는 경우, 특히 인용되지 않은 필드와 혼합된 경우 이를 효과적으로 수행하는 간단한 방법은 없습니다.
또한 열 이름을 입력하여 행을 사전으로 변환하고 싶을 수도 있습니다.
이를 수행하는 내 코드는 수백 줄 길이입니다.
웹이나 오픈소스 프로젝트 등에 몇 가지 예가 있는 것 같아요.
이 시도;
static IEnumerable<string> CsvParse(string input)
{
// null strings return a one-element enumeration containing null.
if (input == null)
{
yield return null;
yield break;
}
// we will 'eat' bits of the string until it's gone.
String remaining = input;
while (remaining.Length > 0)
{
if (remaining.StartsWith("\"")) // deal with quotes
{
remaining = remaining.Substring(1); // pass over the initial quote.
// find the end quote.
int endQuotePosition = remaining.IndexOf("\"");
switch (endQuotePosition)
{
case -1:
// unclosed quote.
throw new ArgumentOutOfRangeException("Unclosed quote");
case 0:
// the empty quote
yield return "";
remaining = remaining.Substring(2);
break;
default:
string quote = remaining.Substring(0, endQuotePosition).Trim();
remaining = remaining.Substring(endQuotePosition + 1);
yield return quote;
break;
}
}
else // deal with commas
{
int nextComma = remaining.IndexOf(",");
switch (nextComma)
{
case -1:
// no more commas -- read to end
yield return remaining.Trim();
yield break;
case 0:
// the empty cell
yield return "";
remaining = remaining.Substring(1);
break;
default:
// get everything until next comma
string cell = remaining.Substring(0, nextComma).Trim();
remaining = remaining.Substring(nextComma + 1);
yield return cell;
break;
}
}
}
}
CsvString.split(',');
모든 줄의 문자열[]을 가져옵니다.
string[] lines = System.IO.File.ReadAllLines("yourfile.csv");
그런 다음 해당 줄을 반복하고 분할합니다(따옴표로 구분된 필드에서 쉼표를 확인하지 않기 때문에 이 오류가 발생하기 쉽습니다).
foreach (string line in lines)
{
string[] items = line.Split({','}};
}
string s = "1,2,3,4,5";
string myStrings[] = s.Split({','}};
Split()은 정렬 분할할 문자 수입니다.
일부 CSV 파일에는 쉼표와 함께 값 주위에 큰따옴표가 있습니다.따라서 때로는 다음 문자열 리터럴로 분할할 수 있습니다.","
인용 필드가 있는 Csv 파일은 Csv 파일이 아닙니다.다른 이름으로 저장에서 "Csv"를 선택하면 따옴표 대신 따옴표 없이 출력되는 항목(Excel)이 훨씬 더 많습니다.
사용, 무료 또는 커밋할 수 있는 것을 원한다면 IDataReader/Record도 수행하는 내 것이 있습니다.또한 DataTable을 사용하여 열과 DbNull을 정의/변환/적용합니다.
http://github.com/claco/csvdatareader/
따옴표는 안 써요..아직.며칠 전 가려움증을 긁기 위해 함께 버렸습니다.
잊혀진 세미콜론:좋은 링크입니다.감사해요.cfeduke:Microsoft.VisualBasic.FileIO.TextFieldParser에 대한 팁을 제공해 주셔서 감사합니다.오늘 밤 CsvDataReader로 이동합니다.
http://github.com/claco/csvdatareader/ cfeduke가 제안한 TextFieldParser를 사용하여 업데이트되었습니다.
구분 기호/트림 공간/유형 ig를 노출하는 데 몇 가지 소품만 있으면 훔칠 코드가 필요합니다.
나는 이미 탭으로 분할하고 있었기 때문에 이것이 나에게 도움이 되었습니다.
public static string CsvToTabDelimited(string line) {
var ret = new StringBuilder(line.Length);
bool inQuotes = false;
for (int idx = 0; idx < line.Length; idx++) {
if (line[idx] == '"') {
inQuotes = !inQuotes;
} else {
if (line[idx] == ',') {
ret.Append(inQuotes ? ',' : '\t');
} else {
ret.Append(line[idx]);
}
}
}
return ret.ToString();
}
string test = "one,two,three";
string[] okNow = test.Split(',');
separationChar[] = {';'}; // or '\t' ',' etc.
var strArray = strCSV.Split(separationChar);
string[] splitStrings = myCsv.Split(",".ToCharArray());