CSVファイルをインポートするためのC#MVCを使用してCSVHelper(NUGET)を使用する

StackOverflow https://stackoverflow.com/questions/5496845

質問

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は自動的に図を似ています プロパティ名を一致させる方法 ヘッダー行に基づいています(このISです 設定可能)コンパイルされています の代わりに表現木 反射、それは非常に速いです。

それはまた非常に拡張可能である 設定可能な

基本的には、ヘッダー(不明な名前)を持つ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