简体   繁体   English

c#在Handler类中从流中读取.csv

[英]c# Read .csv from stream in Handler class

I am using Valum's AJAX File Uploader to upload the csv file. 我正在使用Valum的AJAX文件上传器上传csv文件。 The code to initialize it is : 初始化它的代码是:

    $(document).ready(function () {          
        var uploader = new qq.FileUploader({
            element: document.getElementById('file-uploader'),
            // path to server-side upload script
            action: 'handlers/PhoneNumberListHandler.ashx',
            buttonTitle: 'Upload Document',
            buttonText: ' Upload',
            allowedExtensions: ['csv'],
            sizeLimit: 1024000, // max size 
        });
    });


<div id="file-uploader"></div>

In c# handler class I have written the following code so far: 在c#handler类中,我到目前为止编写了以下代码:

    HttpRequest request = context.Request;
    byte[] buffer = new byte[request.ContentLength];
    Stream inputStream;
    string fileName;

    inputStream = request.InputStream;
    fileName = request["qqfile"];

    using (var reader = new StreamReader(inputStream))
    {
        while (!reader.EndOfStream)
        {
            var line = reader.ReadLine();
            var values = line.Split(';'); // gives some abstract characters
        }
    }

My csv file have three columns Phone, Firstname, Lastname where first column is compulsory and rest are optional. 我的csv文件有三列Phone,Firstname,Lastname,其中第一列是强制的,rest是可选的。

I am now stuck as I am not able to read the .csv file. 我现在卡住了,因为我无法读取.csv文件。 Can someone please help me and suggest how can I read a csv file content from the stream or is there any other way to do it? 有人可以帮助我并建议我如何从流中读取csv文件内容或有其他方法可以做到吗? I want to extract the csv content and save each line separately in database table. 我想提取csv内容并在数据库表中单独保存每一行。

Update: I made changes in saving the csv file and now the content look like this: 更新:我在保存csv文件时进行了更改,现在内容如下所示:

PhoneNumber,FirstName,LastName ******中国,名字,姓氏

11111,Taj,Mahal 11111,泰姬陵,泰姬陵

22222,Oberai, 22222,Oberai,

33333,,Lake Palace 湖宫,33333

44444,, 44444 ,,

Modified the above code: 修改了上面的代码:

    using (var reader = new StreamReader(inputStream))
    {
        List<string> listA = new List<string>();            
        while (!reader.EndOfStream)
        {
            var line = reader.ReadLine();
            var values = line.Split(';');

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

I want to get the individual value of the columns and here I am getting a full line in one string. 我想得到列的单个值,这里我在一个字符串中得到一个完整的行。 To get individual value I have to further split it with "," and get the values. 为了获得个人价值,我必须用“,”进一步拆分它,并获得值。 I want to know is there a better way to do this? 我想知道有更好的方法吗?

Converting CSV file to model with reflection. 将CSV文件转换为带反射的模型。 First of all you could create model and set attributes with Name of CSV columns. 首先,您可以使用CSV列名称创建模型和设置属性。 like this: 像这样:

     public class UserInfo
    {
        [CSVColumn(ImportName = "FirstName"]
        public string FirstName { get; set; }

        [CSVColumn(ImportName = "LastName"]
        public string LastName { get; set; }

        [CSVColumn(ImportName = "PhoneNumber"]
        public string PhoneNumber { get; set; }
    }

Other steps are reading first line for getting data about columns and based on property attributes of model set data from scv row to each model property: 其他步骤是读取第一行以获取有关列的数据,并基于模型集数据的属性属性从scv行到每个模型属性:

     List<UserInfo> users = new List<UserInfo>();
     using (var reader = new StreamReader(inputStream))
            {
                //read first line with headers
                var metaDataLine = reader.ReadLine() ?? "";
                //get array with headers
                string[] csvMetada = metaDataLine.Split(',');  

                   while (!reader.EndOfStream)
                    { 
                     // create model based on string data and columns metadata with columns                      
                     UserInfo newModel =   ConvertCSVToEntity(reader.ReadLine() ?? "", csvMetada);
                     users.add(newModel);
                    }
                }

converting method string csv row to model : 将方法字符串csv row转换为model:

        public UserInfo convertCSVToEntity(string line, string[] csvMetada)
        {
            var values = line.Split(',');

            UserInfo newRecord = ConvertorHelper.ConvertCSVToEntity<UserInfo>(values, csvMetada);

            return newRecord;
        }


        public static T ConvertCSVToEntity<T>(string[] csvData, string[] csvMetada) where T : new()
        {
            T returnEntity = new T();
            var properties = returnEntity.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (var eachProperty in properties)
            {
                var csvAttribute = eachProperty.GetCustomAttribute(typeof(CSVColumn)) as CSVColumn;
                if (csvAttribute != null)
                {
                    int csvIndex = Array.IndexOf(csvMetada, csvAttribute.ImportName);
                    if (csvIndex > -1)
                    {
                        var csvValue = csvData[csvIndex];

                        object setValue = null;
                        try
                        {
                            setValue = string.IsNullOrEmpty(csvValue) && eachProperty.PropertyType != typeof(string) ? Activator.CreateInstance(eachProperty.PropertyType) : Convert.ChangeType(csvValue, eachProperty.PropertyType, ParseCulture);
                        }
                        catch (Exception e)
                        {
                        }
                }
            }

            return returnEntity;
        }

Attributes class 属性类

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]  



 public class CSVColumn : Attribute
    {
        public string ImportName { set; get; }

        public CSVColumn() { }

        public CSVColumn(string _import)
        {
            this.ImportName = _import;

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM