如何垂直读取csv文件记录

时间:2015-04-13 06:21:42

标签: c#

我想将以下文件数据导入数据库

 Id    Name 
10001 Hemant Desai

作为常规表数据,所以如何读取这些数据我在这里有些困惑。

这里是csv文件数据....

ID=,10001,
Name=,Hemant Desai, 
Age=,60,
Sex=,male,
Doctor=,Pathak,
Mobile=,9021412202,
Alignment=,brain tumour,
No of medicins=,3,
12:02,Stamlo-5,1mg,oral,after meal,*XE0280916*
12:01,Atorfit-CV-10,4mg,oral,after meal,*XE0283337*
12:01,Losar,3mg,oral,after meal,*XE0284350*
12:02,Appointment,X ray of right chest at 11.00 am on Wed 11th Dec
12:01,procedure,Sponge patient with warm water
Temperature =,222
Blood Pressure =, 555/555
Pulse Rate =, 555
Respiratory Rate =, 999

并且在医药领域中,我必须将所有数据写入温度场,并在它们之间放置quamma并删除所有=符号

我尝试使用以下代码

public void import()         {             尝试             {                 con.Open();                 string sourceDir = @“目录路径”;                 var IcsvFile = Directory.EnumerateFiles(sourceDir,“* .csv”);                 DataTable dt = new DataTable();              // string line1,line8;

            foreach (string currentFile in IcsvFile)
            {
                //string filename = @"FullFileNameWithPath.csv";
                //get all lines from csv file
                string[] lines = File.ReadAllLines(currentFile);
                //get only id's
                var ids = lines
                    .Where(a => a.Trim() != string.Empty && a.Contains("ID="))
                    .Select((a, x) => new { ID = Convert.ToInt32(a.Split(',')[1]), index = x });
                //get names
                var names = lines
                    .Where(a => a.Trim() != string.Empty && a.Contains("Name="))
                    .Select((a, x) => new { Name = a.Split(',')[1], index = x });
                //get patiens; join ids and names on index
                var patients = from id in ids
                               join name in names on id.index equals name.index
                               select new
                               {
                                   ID = id.ID,
                                   Name = name.Name
                               };
                foreach (var p in patients)
                {
                    Console.WriteLine("{0}\t{1}", p.ID, p.Name);
                }

                //DataTable dt = new DataTable();
                //DataRow row;

                //using (StreamReader sr = new StreamReader(currentFile))
                //{
                //    line1 = sr.ReadLine();
                //    line8 = sr.ReadLine();
                //}
            }

        }

1 个答案:

答案 0 :(得分:0)

您可能知道,这不是使用csv存储数据的正确方法。您将不得不编写一个代码来遍历csv的每一行并解析它。 首先使用System.IO.File.ReadAllLines(FilePath)将整个文件读入字符串数组,然后分析字符串。我建议使用DataTable(假设您的列名是固定的)请注意,如果它包含=字符,则必须检查数组中的每个字符串,如果包含{1}}字符,那么之前是什么这个char是列名,后面是数据。如果没有,请使用最后一列并将整行的数据附加到其当前数据中。

完成后,您应该有一个DataTable,其中包含来自“csv”的所有数据。文件。然后,您只需将其发送到将添加或更新数据库中数据的存储过程。

以下是我可能会做的事情:

    private DataTable ReadFiles(string sourceDir)
    {
        var IcsvFile = Directory.EnumerateFiles(sourceDir, "*.csv");
        DataTable dt = new DataTable();
        dt.Columns.Add("Id", System.Type.GetType("System.Int32"));
        dt.Columns.Add("Name", System.Type.GetType("System.String"));
        dt.Columns.Add("Age", System.Type.GetType("System.Int32"));
        dt.Columns.Add("Sex", System.Type.GetType("System.String")); // Gender in proper english 
        dt.Columns.Add("Doctor", System.Type.GetType("System.String"));
        dt.Columns.Add("Mobile", System.Type.GetType("System.String"));
        dt.Columns.Add("Alignment", System.Type.GetType("System.String"));
        dt.Columns.Add("No of medicins", System.Type.GetType("System.String"));
        dt.Columns.Add("Temperature ", Type.GetType("System.Int32"));
        dt.Columns.Add("Blood Pressure", System.Type.GetType("System.String"));
        dt.Columns.Add("Pulse Rate", System.Type.GetType("System.String"));
        dt.Columns.Add("Respiratory Rate", System.Type.GetType("System.Int32"));
        foreach (string currentFile in IcsvFile)
        {
            ImportSingleFile(currentFile, ref dt);
        }
        return dt;
    }

    private void ImportSingleFile(string FilePath, ref DataTable dt)
    {
        string[] Lines = File.ReadAllLines(FilePath);
        string ColumnName, ColumnData;
        int EqualSignIndex, intColumnData;
        DataRow Row = null;
        ColumnName = string.Empty;
        foreach (string Line in Lines)
        {
            EqualSignIndex = Line.IndexOf("=");
            if (EqualSignIndex > -1)
            {
                ColumnName = Line.Substring(0, EqualSignIndex);
                // after = there is always , that we don't want in the data, 
                // and the line sometimes ends with a , that we also don't want
                ColumnData = Line.Substring(EqualSignIndex + 2).TrimEnd(','); 
            }
            else
            {
                ColumnData = Line;
            }

            if (ColumnName == "ID")
            {
                Row = dt.NewRow();
            }

            if (Row != null)
            {
                if(dt.Columns[ColumnName].DataType == Type.GetType("System.Int32")) {
                    if(int.TryParse(ColumnData, out intColumnData)) 
                    {
                        Row[ColumnName] = intColumnData;
                    } else {
                        throw new InvalidDataException(string.Format("For column {0} an integer value is expected", ColumnName));
                    }
                } else {
                    Row[ColumnName] = ColumnData;
                }                   
            }
        }
    }

之后你应该把数据表填满,从中插入/更新数据库应该很容易。