sourcetip

CSV 파일 읽기 및 배열에 값 저장

fileupload 2023. 5. 23. 22:21
반응형

CSV 파일 읽기 및 배열에 값 저장

나는 읽으려고 노력하고 있습니다.*.csv -file.

*.csv-file은 세미콜론(";")으로 구분된 두 개의 열로 구성됩니다.

▁the다▁read니를 읽을 수 있습니다.*.csv하며 -StreamReader를 각할 수 .Split()기능.을 별도의 한 다음 각 열을 별도의 배열로 저장한 다음 표시하려고 합니다.

그것이 가능합니까?

다음과 같이 할 수 있습니다.

using System.IO;

static void Main(string[] args)
{
    using(var reader = new StreamReader(@"C:\test.csv"))
    {
        List<string> listA = new List<string>();
        List<string> listB = new List<string>();
        while (!reader.EndOfStream)
        {
            var line = reader.ReadLine();
            var values = line.Split(';');

            listA.Add(values[0]);
            listB.Add(values[1]);
        }
    }
}

제가 가장 좋아하는 CSV 파서는 .NET 라이브러리에 내장된 파서입니다.이것은 마이크로소프트 내부에 숨겨진 보물입니다.VisualBasic 네임스페이스입니다.다음은 샘플 코드입니다.

using Microsoft.VisualBasic.FileIO;

var path = @"C:\Person.csv"; // Habeeb, "Dubai Media City, Dubai"
using (TextFieldParser csvParser = new TextFieldParser(path))
{
 csvParser.CommentTokens = new string[] { "#" };
 csvParser.SetDelimiters(new string[] { "," });
 csvParser.HasFieldsEnclosedInQuotes = true;

 // Skip the row with the column names
 csvParser.ReadLine();

 while (!csvParser.EndOfData)
 {
  // Read current line fields, pointer moves to the next line.
  string[] fields = csvParser.ReadFields();
  string Name = fields[0];
  string Address = fields[1];
 }
}

다에참조추합니다야해가를에 대한 참조를 하는 것을 하세요.Microsoft.VisualBasic

파서에 대한 자세한 내용은 http://codeskaters.blogspot.ae/2015/11/c-easiest-csv-parser-built-in-net.html 에서 확인할 수 있습니다.

LINQ 방식:

var lines = File.ReadAllLines("test.txt").Select(a => a.Split(';'));
var csv = from line in lines
          select (from piece in line
                  select piece);

^^ 편집자 - Nick 편집

원래 응답자가 정보를 입력하려고 시도한 것 같습니다.csv배열을 포함하는 배열인 2차원 배열을 사용합니다.첫 번째 배열의 각 항목에는 해당 열에 대한 데이터를 포함하는 중첩 배열의 각 항목과 함께 해당 줄 번호를 나타내는 배열이 포함됩니다.

var csv = from line in lines
          select (line.Split(',')).ToArray();

방금 이 라이브러리를 발견했습니다: https://github.com/JoshClose/CsvHelper

매우 직관적이고 사용하기 쉽습니다.구현이 빠른 뉘트 패키지도 있습니다. https://www.nuget.org/packages/CsvHelper/27.2.1 .또한 제가 좋아하는 것을 적극적으로 유지하고 있는 것 같습니다.

반선호도를 사용하도록 구성하는 것은 간단합니다. https://github.com/JoshClose/CsvHelper/wiki/Custom-Configurations

처음부터 행 수를 알아야 하므로 어레이를 즉시 생성할 수 없습니다(이 경우 CSV 파일을 두 번 읽어야 함).

은 두 개의 을두개저수있다로 할 수 .List<T>그런 다음 사용하거나 다음을 사용하여 배열로 변환합니다.List<T>.ToArray()

매우 간단한 예:

var column1 = new List<string>();
var column2 = new List<string>();
using (var rd = new StreamReader("filename.csv"))
{
    while (!rd.EndOfStream)
    {
        var splits = rd.ReadLine().Split(';');
        column1.Add(splits[0]);
        column2.Add(splits[1]);
    }
}
// print column1
Console.WriteLine("Column 1:");
foreach (var element in column1)
    Console.WriteLine(element);

// print column2
Console.WriteLine("Column 2:");
foreach (var element in column2)
    Console.WriteLine(element);

N.B.

이것은 아주 간단한 예일 뿐입니다.사용.string.Split 레코드에 기호가 .;안에. 에안그안.
더 안전한 접근 방식을 위해 nuget에서 CsvHelper와 같은 일부 csv 관련 라이브러리를 사용하는 것을 고려하십시오.

저는 주로 코드 프로젝트에서 이 파서를 사용합니다. 왜냐하면 캐릭터 탈출과 저를 위해 처리되는 유사한 것들이 많기 때문입니다.

다음은 제가 투표한 상위 답변의 변형입니다.

var contents = File.ReadAllText(filename).Split('\n');
var csv = from line in contents
          select line.Split(',').ToArray();

csv그런 다음 변수를 다음 예제와 같이 사용할 수 있습니다.

int headerRows = 5;
foreach (var row in csv.Skip(headerRows)
    .TakeWhile(r => r.Length > 1 && r.Last().Trim().Length > 0))
{
    String zerothColumnValue = row[0]; // leftmost column
    var firstColumnValue = row[1];
}

선 및/또는 열을 건너뛰어야 하는 경우 이를 사용하여 2차원 배열을 작성할 수 있습니다.

    var lines = File.ReadAllLines(path).Select(a => a.Split(';'));
    var csv = (from line in lines               
               select (from col in line
               select col).Skip(1).ToArray() // skip the first column
              ).Skip(2).ToArray(); // skip 2 headlines

이는 데이터를 추가로 처리하기 전에 데이터 모양을 만들어야 하는 경우에 매우 유용합니다(처음 두 줄은 헤드라인으로 구성되어 있고 첫 번째 열은 행 제목이라고 가정하면 데이터를 고려하기 때문에 배열에 포함할 필요가 없습니다).

N.B. 다음 코드를 사용하면 헤드라인과 첫 번째 열을 쉽게 얻을 수 있습니다.

    var coltitle = (from line in lines 
                    select line.Skip(1).ToArray() // skip 1st column
                   ).Skip(1).Take(1).FirstOrDefault().ToArray(); // take the 2nd row
    var rowtitle = (from line in lines select line[0] // take 1st column
                   ).Skip(2).ToArray(); // skip 2 headlines

의 이코예다같가구다의 가정합니다.*.csv파일 이름:

CSV 매트릭스

참고: 빈 행을 건너뛰어야 하는 경우 - 때때로 편리하게 사용할 수 있습니다.

    where line.Any(a=>!string.IsNullOrWhiteSpace(a))

from 리고그고.select위의 LINQ 코드 예제에 있는 문장.

Microsoft를 사용할 수 있습니다.Visual Basic.성능 향상을 위한 C#의 FileIO.TextFieldParser dll

위의 기사에서 아래 코드 예제 가져오기

static void Main()
{
    string csv_file_path=@"C:\Users\Administrator\Desktop\test.csv";

    DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);

    Console.WriteLine("Rows count:" + csvData.Rows.Count);

    Console.ReadLine();
}


private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
    DataTable csvData = new DataTable();

    try
    {

    using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
        {
            csvReader.SetDelimiters(new string[] { "," });
            csvReader.HasFieldsEnclosedInQuotes = true;
            string[] colFields = csvReader.ReadFields();
            foreach (string column in colFields)
            {
                DataColumn datecolumn = new DataColumn(column);
                datecolumn.AllowDBNull = true;
                csvData.Columns.Add(datecolumn);
            }

            while (!csvReader.EndOfData)
            {
                string[] fieldData = csvReader.ReadFields();
                //Making empty value as null
                for (int i = 0; i < fieldData.Length; i++)
                {
                    if (fieldData[i] == "")
                    {
                        fieldData[i] = null;
                    }
                }
                csvData.Rows.Add(fieldData);
            }
        }
    }
    catch (Exception ex)
    {
    }
    return csvData;
}

안녕하세요, 저는 이것을 하기 위해 정적인 수업을 만들었습니다.열 확인 + 할당량 표시 제거

public static class CSV
{
    public static List<string[]> Import(string file, char csvDelimiter, bool ignoreHeadline, bool removeQuoteSign)
    {
        return ReadCSVFile(file, csvDelimiter, ignoreHeadline, removeQuoteSign);
    }

    private static List<string[]> ReadCSVFile(string filename, char csvDelimiter, bool ignoreHeadline, bool removeQuoteSign)
    {
        string[] result = new string[0];
        List<string[]> lst = new List<string[]>();

        string line;
        int currentLineNumner = 0;
        int columnCount = 0;

        // Read the file and display it line by line.  
        using (System.IO.StreamReader file = new System.IO.StreamReader(filename))
        {
            while ((line = file.ReadLine()) != null)
            {
                currentLineNumner++;
                string[] strAr = line.Split(csvDelimiter);
                // save column count of dirst line
                if (currentLineNumner == 1)
                {
                    columnCount = strAr.Count();
                }
                else
                {
                    //Check column count of every other lines
                    if (strAr.Count() != columnCount)
                    {
                        throw new Exception(string.Format("CSV Import Exception: Wrong column count in line {0}", currentLineNumner));
                    }
                }

                if (removeQuoteSign) strAr = RemoveQouteSign(strAr);

                if (ignoreHeadline)
                {
                    if(currentLineNumner !=1) lst.Add(strAr);
                }
                else
                {
                    lst.Add(strAr);
                }
            }

        }

        return lst;
    }
    private static string[] RemoveQouteSign(string[] ar)
    {
        for (int i = 0;i< ar.Count() ; i++)
        {
            if (ar[i].StartsWith("\"") || ar[i].StartsWith("'")) ar[i] = ar[i].Substring(1);
            if (ar[i].EndsWith("\"") || ar[i].EndsWith("'")) ar[i] = ar[i].Substring(0,ar[i].Length-1);

        }
        return ar;
    }

}

올바른 라이브러리를 찾는 데 몇 시간이 걸렸지만 마침내 코드를 작성했습니다 :) 원하는 도구로 파일(또는 데이터베이스)을 읽고 각 줄에 다음 루틴을 적용할 수 있습니다.

private static string[] SmartSplit(string line, char separator = ',')
{
    var inQuotes = false;
    var token = "";
    var lines = new List<string>();
    for (var i = 0; i < line.Length; i++) {
        var ch = line[i];
        if (inQuotes) // process string in quotes, 
        {
            if (ch == '"') {
                if (i<line.Length-1 && line[i + 1] == '"') {
                    i++;
                    token += '"';
                }
                else inQuotes = false;
            } else token += ch;
        } else {
            if (ch == '"') inQuotes = true;
            else if (ch == separator) {
                lines.Add(token);
                token = "";
                } else token += ch;
            }
    }
    lines.Add(token);
    return lines.ToArray();
}
var firstColumn = new List<string>();
var lastColumn = new List<string>();

// your code for reading CSV file

foreach(var line in file)
{
    var array = line.Split(';');
    firstColumn.Add(array[0]);
    lastColumn.Add(array[1]);
}

var firstArray = firstColumn.ToArray();
var lastArray = lastColumn.ToArray();

다음은 데이터 필드 중 하나에 세미콜론(";")이 데이터의 일부로 포함되어 있는 특별한 경우입니다. 이 경우 위의 답변 대부분이 실패합니다.

이 경우의 해결책은 다음과 같습니다.

string[] csvRows = System.IO.File.ReadAllLines(FullyQaulifiedFileName);
string[] fields = null;
List<string> lstFields;
string field;
bool quoteStarted = false;
foreach (string csvRow in csvRows)
{
    lstFields = new List<string>();
    field = "";
    for (int i = 0; i < csvRow.Length; i++)
    {
        string tmp = csvRow.ElementAt(i).ToString();
        if(String.Compare(tmp,"\"")==0)
        {
            quoteStarted = !quoteStarted;
        }
        if (String.Compare(tmp, ";") == 0 && !quoteStarted)
        {
            lstFields.Add(field);
            field = "";
        }
        else if (String.Compare(tmp, "\"") != 0)
        {
            field += tmp;
        }
    }
    if(!string.IsNullOrEmpty(field))
    {
        lstFields.Add(field);
        field = "";
    }
// This will hold values for each column for current row under processing
    fields = lstFields.ToArray(); 
}

오픈 소스 Angara.테이블 라이브러리를 사용하면 CSV를 입력된 열에 로드할 수 있으므로 열에서 배열을 가져올 수 있습니다.각 열은 이름 또는 색인으로 인덱싱될 수 있습니다.http://predictionmachines.github.io/Angara.Table/saveload.html 을 참조하십시오.

이 라이브러리는 CSV용 RFC4180을 따릅니다. 유형 추론 및 다중 줄 문자열을 사용할 수 있습니다.

예:

using System.Collections.Immutable;
using Angara.Data;
using Angara.Data.DelimitedFile;

...

ReadSettings settings = new ReadSettings(Delimiter.Semicolon, false, true, null, null);
Table table = Table.Load("data.csv", settings);
ImmutableArray<double> a = table["double-column-name"].Rows.AsReal;

for(int i = 0; i < a.Length; i++)
{
    Console.WriteLine("{0}: {1}", i, a[i]);
}

예를 들어 열 유형을 사용하여 열 유형을 볼 수 있습니다.

Column c = table["double-column-name"];
Console.WriteLine("Column {0} is double: {1}", c.Name, c.Rows.IsRealColumn);

라이브러리가 F#에 초점을 맞추고 있으므로 FSharp에 참조를 추가해야 할 수 있습니다.Core 4.4 어셈블리. 프로젝트에서 '참조 추가'를 클릭하고 FSharp를 선택합니다.코어 4.4의 "어셈블리" -> "확장" 아래에 있습니다.

저는 수년간 csvreader.com (유료 부품)을 사용해 왔으며 문제가 발생한 적이 없습니다.그것은 견고하고 작고 빠릅니다, 하지만 당신은 그것을 위해 돈을 지불해야 합니다.구분 기호를 원하는 대로 설정할 수 있습니다.

using (CsvReader reader = new CsvReader(s) {
    reader.Settings.Delimiter = ';';
    reader.ReadHeaders();  // if headers on a line by themselves.  Makes reader.Headers[] available
    while (reader.ReadRecord())
        ... use reader.Values[col_i] ...
}

저는 석사 논문을 쓰고 있는 학생일 뿐이지만, 이것이 제가 해결한 방법이고 저에게 잘 맞았습니다.먼저 디렉토리(csv 형식만)에서 파일을 선택한 다음 데이터를 목록에 넣습니다.

List<float> t = new List<float>();
List<float> SensorI = new List<float>();
List<float> SensorII = new List<float>();
List<float> SensorIII = new List<float>();
using (OpenFileDialog dialog = new OpenFileDialog())
{
    try
    {
        dialog.Filter = "csv files (*.csv)|*.csv";
        dialog.Multiselect = false;
        dialog.InitialDirectory = ".";
        dialog.Title = "Select file (only in csv format)";
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            var fs = File.ReadAllLines(dialog.FileName).Select(a => a.Split(';'));
            int counter = 0;
            foreach (var line in fs)
            {
                counter++;
                if (counter > 2)    // Skip first two headder lines
                {
                    this.t.Add(float.Parse(line[0]));
                    this.SensorI.Add(float.Parse(line[1]));
                    this.SensorII.Add(float.Parse(line[2]));
                    this.SensorIII.Add(float.Parse(line[3]));
                }
            }
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(
            "Error while opening the file.\n" + exc.Message, 
            this.Text, 
            MessageBoxButtons.OK, 
            MessageBoxIcon.Error
        );
    }
}

이것은 csv 파일에서 텍스트를 다음으로 변환하는 의 간단한 정적 방법 2가지입니다.List<List<string>>그리고 역도 성립.각 방법은 행 변환기를 사용합니다.

이 코드는 csv 파일의 모든 가능성을 고려해야 합니다.고유한 csv 구분 기호를 정의할 수 있으며 이 방법은 이스케이프 이중 '따옴표' 문자를 수정하려고 시도하며, 따옴표의 모든 텍스트가 하나의 에 있고 csv 구분 기호가 하나의 셀에 여러 줄을 포함하는 따옴표 문자열 내부에 있으며을 무시할 수 있는 상황을 처리합니다.

마지막 방법은 테스트용입니다.따라서 이 테스트 방법을 사용하여 이를 무시하거나 자신의 솔루션 또는 다른 솔루션을 테스트할 수 있습니다. :).테스트를 위해 이 하드 csv를 4줄에 2줄로 사용했습니다.

0,a,""bc,d
"e, f",g,"this,is, o
ne ""lo
ng, cell""",h

이것이 최종 코드입니다.단순화를 위해 모든 시도 캐치 블록을 제거했습니다.

using System;
using System.Collections.Generic;
using System.Linq;

public static class Csv {
  public static string FromListToString(List<List<string>> csv, string separator = ",", char quotation = '"', bool returnFirstRow = true)
  {
    string content = "";
    for (int row = 0; row < csv.Count; row++) {
      content += (row > 0 ? Environment.NewLine : "") + RowFromListToString(csv[row], separator, quotation);
    }
    return content;
  }

  public static List<List<string>> FromStringToList(string content, string separator = ",", char quotation = '"', bool returnFirstRow = true, bool ignoreEmptyRows = true)
  {
    List<List<string>> csv = new List<List<string>>();
    string[] rows = content.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
    if (rows.Length <= (returnFirstRow ? 0 : 1)) { return csv; }
    List<string> csvRow = null;
    for (int rowIndex = 0; rowIndex < rows.Length; rowIndex++) {
      (List<string> row, bool rowClosed) = RowFromStringToList(rows[rowIndex], csvRow, separator, quotation);
      if (rowClosed) { if (!ignoreEmptyRows || row.Any(rowItem => rowItem.Length > 0)) { csv.Add(row); csvRow = null; } } // row ok, add to list
      else { csvRow = row; } // not fully created, continue
    }
    if (!returnFirstRow) { csv.RemoveAt(0); } // remove header
    return csv;
  }

  public static string RowFromListToString(List<string> csvData, string separator = ",", char quotation = '"')
  {
    csvData = csvData.Select(element =>
    {
      if (element.Contains(quotation)) {
        element = element.Replace(quotation.ToString(), quotation.ToString() + quotation.ToString());
      }
      if (element.Contains(separator) || element.Contains(Environment.NewLine)) {
        element = "\"" + element + "\"";
      }
      return element;
    }).ToList();
    return string.Join(separator, csvData);
  }

  public static (List<string>, bool) RowFromStringToList(string csvRow, List<string> continueWithRow = null, string separator = ",", char quotation = '"')
  {
    bool rowClosed = true;
    if (continueWithRow != null && continueWithRow.Count > 0) {
      // in previous result quotation are fixed so i need convert back to double quotation
      string previousCell = quotation.ToString() + continueWithRow.Last().Replace(quotation.ToString(), quotation.ToString() + quotation.ToString()) + Environment.NewLine;
      continueWithRow.RemoveAt(continueWithRow.Count - 1);
      csvRow = previousCell + csvRow;
    }

    char tempQuote = (char)162;
    while (csvRow.Contains(tempQuote)) { tempQuote = (char)(tempQuote + 1); }
    char tempSeparator = (char)(tempQuote + 1);
    while (csvRow.Contains(tempSeparator)) { tempSeparator = (char)(tempSeparator + 1); }

    csvRow = csvRow.Replace(quotation.ToString() + quotation.ToString(), tempQuote.ToString());
    if(csvRow.Split(new char[] { quotation }, StringSplitOptions.None).Length % 2 == 0) { rowClosed = !rowClosed; }
    string[] csvSplit = csvRow.Split(new string[] { separator }, StringSplitOptions.None);

    List<string> csvList = csvSplit
      .ToList()
      .Aggregate("",
          (string row, string item) => {
              if (row.Count((ch) => ch == quotation) % 2 == 0) { return row + (row.Length > 0 ? tempSeparator.ToString() : "") + item; }
              else { return row + separator + item; }
          },
          (string row) => row.Split(tempSeparator).Select((string item) => item.Trim(quotation).Replace(tempQuote, quotation))
      ).ToList();
    if (continueWithRow != null && continueWithRow.Count > 0) {
      return (continueWithRow.Concat(csvList).ToList(), rowClosed);
    }
    return (csvList, rowClosed);
  }

  public static bool Test()
  {
    string csvText = "0,a,\"\"bc,d" + Environment.NewLine + "\"e, f\",g,\"this,is, o" + Environment.NewLine + "ne \"\"lo" + Environment.NewLine + "ng, cell\"\"\",h";
    List<List<string>> csvList = new List<List<string>>() { new List<string>() { "0", "a", "\"bc", "d" }, new List<string>() { "e, f", "g", "this,is, o" + Environment.NewLine + "ne \"lo" + Environment.NewLine + "ng, cell\"", "h" } };

    List<List<string>> csvTextAsList = Csv.FromStringToList(csvText);
    bool ok = Enumerable.SequenceEqual(csvList[0], csvTextAsList[0]) && Enumerable.SequenceEqual(csvList[1], csvTextAsList[1]);
    string csvListAsText = Csv.FromListToString(csvList);
    return ok && csvListAsText == csvText;
  }
}

사용 예:

// get List<List<string>> representation of csv
var csvFromText = Csv.FromStringToList(csvAsText);

// read csv file with custom separator and quote
// return no header and ignore empty rows
var csvFile = File.ReadAllText(csvFileFullPath);
var csvFromFile = Csv.FromStringToList(csvFile, ";", '"', false, false);

// get text representation of csvData from List<List<string>>
var csvAsText = Csv.FromListToString(csvData);

사항
다음 항목:char tempQuote = (char)162;ASCI 테이블의 첫 번째 희귀 문자입니다.스크립트는 이 문자 또는 텍스트에 없는 처음 몇 개의 ASCII 문자를 검색하여 임시 이스케이프 및 따옴표 문자로 사용합니다.

여전히 틀렸습니다.견적서의 ""에 대한 보상이 필요합니다.Microsoft 스타일 CSV 솔루션을 소개합니다.

               /// <summary>
    /// Microsoft style csv file.  " is the quote character, "" is an escaped quote.
    /// </summary>
    /// <param name="fileName"></param>
    /// <param name="sepChar"></param>
    /// <param name="quoteChar"></param>
    /// <param name="escChar"></param>
    /// <returns></returns>
    public static List<string[]> ReadCSVFileMSStyle(string fileName, char sepChar = ',', char quoteChar = '"')
    {
        List<string[]> ret = new List<string[]>();

        string[] csvRows = System.IO.File.ReadAllLines(fileName);

        foreach (string csvRow in csvRows)
        {
            bool inQuotes = false;
            List<string> fields = new List<string>();
            string field = "";
            for (int i = 0; i < csvRow.Length; i++)
            {
                if (inQuotes)
                {
                    // Is it a "" inside quoted area? (escaped litteral quote)
                    if(i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i+1] == quoteChar)
                    {
                        i++;
                        field += quoteChar;
                    }
                    else if(csvRow[i] == quoteChar)
                    {
                        inQuotes = false;
                    }
                    else
                    {
                        field += csvRow[i];
                    }
                }
                else // Not in quoted region
                {
                     if (csvRow[i] == quoteChar)
                    {
                        inQuotes = true;
                    }
                    if (csvRow[i] == sepChar)
                    {
                        fields.Add(field);
                        field = "";
                    }
                    else 
                    {
                        field += csvRow[i];
                    }
                }
            }
            if (!string.IsNullOrEmpty(field))
            {
                fields.Add(field);
                field = "";
            }
            ret.Add(fields.ToArray());
        }

        return ret;
    }
}

당신이 필요로 하는 것을 정확히 하고 있는 도서관이 있습니다.

얼마 전에 CSV 파일로 작업할 수 있을 정도로 간단하고 빠른 라이브러리를 작성했습니다.다음 링크에서 찾을 수 있습니다. https://github.com/ukushu/DataExporter/blob/master/Csv.cs

2차원 어레이와 마찬가지로 CSV에서도 작동합니다.당신이 필요로 하는 그대로.

예를 들어, 세 번째 행의 모든 값이 필요한 경우 다음과 같이 쓰면 됩니다.

Csv csv = new Csv();

csv.FileOpen("c:\\file1.csv");

var allValuesOf3rdRow = csv.Rows[2];

또는 세 번째 행의 두 번째 셀을 읽습니다.

var value = csv.Rows[2][1];

아래 코드에서 json 변환의 경우 csv에 헤더가 필요합니다.

아래 코드는 변경 없이 그대로 사용하실 수 있습니다.

이 코드는 두 행 머리글 또는 한 행 머리글과 함께 작동합니다.

여기에 이미지 설명 입력

아래 코드는 업로드된 IForm File을 읽고 메모리 스트림으로 변환합니다.

업로드된 파일 대신 파일 경로를 사용하려면 대체할 수 있습니다.

새 스트림 판독기(ms, 시스템).텍스트, 인코딩.UTF8, true), 새 스트림 판독기(".../../예시 파일 경로") 포함;

using (var ms = new MemoryStream())
{
    administrativesViewModel.csvFile.CopyTo(ms);
    ms.Position = 0;
    using (StreamReader csvReader = new StreamReader(ms, System.Text.Encoding.UTF8, true))
    {
        List<string> lines = new List<string>();
        while (!csvReader.EndOfStream)
        {
            var line = csvReader.ReadLine();
            var values = line.Split(';');
            if (values[0] != "" && values[0] != null)
            {
                lines.Add(values[0]);
            }
        }
        var csv = new List<string[]>();
        foreach (string item in lines)
        {
            csv.Add(item.Split(','));
        }
        var properties = lines[0].Split(',');
        int csvI = 1;
        var listObjResult = new List<Dictionary<string, string>>();
        if (lines.Count() > 1)
        {
            var ln = lines[0].Substring(0, lines[0].Count() - 1);
            var ln1 = lines[1].Substring(0, lines[1].Count() - 1);
            var lnSplit = ln.Split(',');
            var ln1Split = ln1.Split(',');
            if (lnSplit.Count() != ln1Split.Count())
            {
                properties = lines[1].Split(',');
                csvI = 2;
            }
        }
        for (int i = csvI; i < csv.Count(); i++)
        {
            var objResult = new Dictionary<string, string>();
            if (csvI > 0)
            {
                var splitProp = lines[0].Split(":");
                if (splitProp.Count() > 1)
                {
                    if (splitProp[0] != "" && splitProp[0] != null && splitProp[1] != "" && splitProp[1] != null)
                    {
                        objResult.Add(splitProp[0], splitProp[1]);
                    }
                }
            }
            for (int j = 0; j < properties.Length; j++)
                if (!properties[j].Contains(":"))
                {
                    objResult.Add(properties[j], csv[i][j]);
                }
            listObjResult.Add(objResult);
        }
        var result = JsonConvert.SerializeObject(listObjResult);
        var result2 = JArray.Parse(result);
        Console.WriteLine(result2);
    }
}

이것 좀 봐요.

CsvFramework 사용;

시스템을 사용합니다.컬렉션.일반;

네임스페이스 CvsParser {}

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Order> Orders { get; set; }        
}

public class Order
{
    public int Id { get; set; }

    public int CustomerId { get; set; }
    public int Quantity { get; set; }

    public int Amount { get; set; }

    public List<OrderItem> OrderItems { get; set; }

}

public class Address
{
    public int Id { get; set; }
    public int CustomerId { get; set; }

    public string Name { get; set; }
}

public class OrderItem
{
    public int Id { get; set; }
    public int OrderId { get; set; }

    public string ProductName { get; set; }
}

class Program
{
    static void Main(string[] args)
    {

        var customerLines = System.IO.File.ReadAllLines(@"Customers.csv");
        var orderLines = System.IO.File.ReadAllLines(@"Orders.csv");
        var orderItemLines = System.IO.File.ReadAllLines(@"OrderItemLines.csv");

        CsvFactory.Register<Customer>(builder =>
        {
            builder.Add(a => a.Id).Type(typeof(int)).Index(0).IsKey(true);
            builder.Add(a => a.Name).Type(typeof(string)).Index(1);
            builder.AddNavigation(n => n.Orders).RelationKey<Order, int>(k => k.CustomerId);

        }, false, ',', customerLines);

        CsvFactory.Register<Order>(builder =>
        {
            builder.Add(a => a.Id).Type(typeof(int)).Index(0).IsKey(true);
            builder.Add(a => a.CustomerId).Type(typeof(int)).Index(1);
            builder.Add(a => a.Quantity).Type(typeof(int)).Index(2);
            builder.Add(a => a.Amount).Type(typeof(int)).Index(3);
            builder.AddNavigation(n => n.OrderItems).RelationKey<OrderItem, int>(k => k.OrderId);

        }, true, ',', orderLines);


        CsvFactory.Register<OrderItem>(builder =>
        {
            builder.Add(a => a.Id).Type(typeof(int)).Index(0).IsKey(true);
            builder.Add(a => a.OrderId).Type(typeof(int)).Index(1);
            builder.Add(a => a.ProductName).Type(typeof(string)).Index(2);


        }, false, ',', orderItemLines);



        var customers = CsvFactory.Parse<Customer>();


    }
}

}

언급URL : https://stackoverflow.com/questions/5282999/reading-csv-file-and-storing-values-into-an-array

반응형