문제

"NuFollow noreferrrer"> http://csvhelper.com nuget을 통해 사용 가능하면 CSV 파일을 읽고 쓸 수 있습니다.

csvhelper를 사용하면 CSV 파일을 사용자 정의 클래스로 직접 읽을 수 있습니다. 다음과 같이

이전 질문

var streamReader = // Create a reader to your CSV file.
var csvReader = new CsvReader( streamReader );
List<MyCustomType> myData = csvReader.GetRecords<MyCustomType>();
.

csvreader가 자동으로 표시됩니다 속성 이름과 일치하는 방법 헤더 행을 기반으로합니다 (이것은 구성 가능). 그것은 컴파일 된 것을 사용합니다 표현 나무 대신 반사, 그래서 그것은 매우 빠릅니다.

또한 매우 확장 가능합니다 구성 가능.

나는 기본적으로 CSV 파일에서 헤더 (알 수없는 이름)로 읽고 사용자 정의 객체로 레코드를 읽는 방법을 노력하고 있습니다.

이 모든 것은 CSVReader를 문자열 배열로 지정하여 값을 지정하는 방법을 알리는 방법을 알고 있거나이를 어떻게 처리하는 것이 좋습니다.

도움이 되었습니까?

해결책

This is my first version, I will update as I amend things and make it more complete but this gives me all the data in string arrays.

   [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase file)
        {

            ICsvParser csvParser = new CsvParser(new StreamReader(file.InputStream));
            CsvReader csvReader = new CsvReader(csvParser);
            string[] headers = {};
            List<string[]> rows = new List<string[]>();
            string[] row;
            while (csvReader.Read())
            {
                // Gets Headers if they exist
                if (csvReader.HasHeaderRecord && !headers.Any())
                {
                    headers = csvReader.FieldHeaders;
                }
                row = new string[headers.Count()];
                for (int j = 0; j < headers.Count(); j++)
                {
                    row[j] = csvReader.GetField(j);
                }
                rows.Add(row);
            }
            ImportViewModel model = new ImportViewModel(rows);
            return View(model);
        }

다른 팁

There is a CsvFieldAttribute that you can put on your property where you can either put the name of csv field, or the index of the csv field. Name will only work if there is a header row in the csv file.

public class MyCustomClass
{
    [CsvField( FieldIndex = 1 )]
    public string Property1 { get; set; }

    [CsvField( FieldIndex = 0 )]
    public string Property2 { get; set; }

    [CsvField( FieldIndex = 2 )]
    public string Property3 { get; set; }
}

If all you want to do is read a record into a string array in the order that it's in in the file, you can just use CsvParser instead of CsvReader. Calling CsvParser.Read() returns a string[]. CsvReader uses CsvParser to read the raw data.

I know this is not related to CVSHelpers but you may like to consider the FileHelpers project

It allows you to decorate fields on an object with attributes so that it represents a row in the csv file and then use a FileHelperEngine to read the file in - resulting in an array of objects each one representing a row

see this quick start on reading delimited files

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top