使用C#将文本文件导入SQL Server数据库

时间:2018-02-20 16:39:25

标签: c# asp.net

我正在尝试将文本文件导入sql server数据库并且导入工作正常,但问题是文本文件中的所有列都插入到一列中。 enter image description here

我需要文本文件中的列来映射sql表中的列。 这是我的代码

Console.WriteLine(s);
         string fileName = s.ToString();
         string fullPath = path + fileName.ToString();

         DataTable dt = new DataTable();
         dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Environment", typeof(string)),
            new DataColumn("Job_Name", typeof(string)),
            new DataColumn("Occurs",typeof(string)) });


         string csvData = File.ReadAllText(fullPath);
         foreach (string row in csvData.Split('\n'))
         {
           if (!string.IsNullOrEmpty(row))
           {
             dt.Rows.Add();
             int i = 0;
             foreach (string cell in row.Split(','))
             {
               dt.Rows[dt.Rows.Count - 1][i] = cell;
               i++;
             }
           }
         }

         string consString = ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;
         using (SqlConnection con = new SqlConnection(consString))
         {
           using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
           {
             //Set the database table name
             sqlBulkCopy.DestinationTableName = "[dbo].[test2]";
             con.Open();
             sqlBulkCopy.WriteToServer(dt);
             con.Close();
           }
         }

2 个答案:

答案 0 :(得分:2)

当您的数据以制表符分隔时,您在逗号上拆分行。而是这样做:

row.Split('\t')

另外,请勿在{{1​​}}上拆分整个文件,例如使用\n

File.ReadAllLines

答案 1 :(得分:0)

下面的 c# 函数将逗号分隔的文件导入到 C# 数据表中。将数据放入 dataTable 后,您可以应用所需的方法(批量插入/逐行)以接收数据库:

 public static DataTable ImportDataFromCSVFile(string filePath)
    {
        DataTable dataTable = new DataTable();
        try
        {
            using (StreamReader readFile = new StreamReader(filePath))
            {
                string line;
                StringBuilder sb = new StringBuilder();
                string[] row;
                int counter = 0;
                int length = 0;
                while ((line = readFile.ReadLine()) != null)
                {
                    row = line.Split(',');

                    if (counter == 0)
                    {
                        length = row.Length;
                        DataRow dr1 = dataTable.NewRow();
                        for (int i = 0; i < length; i++)
                        {
                            try
                            {
                                //dataTable.Columns.Add("Col_" + i.ToString());
                                dataTable.Columns.Add(Convert.ToString(row[i]));

                            }
                            catch (Exception ex)
                            {

                            }
                        }
                        //  dataTable.Rows.Add(dr1);
                    }
                    else
                    {
                        if (row.Length == dataTable.Columns.Count)
                        {
                            DataRow dr = dataTable.NewRow();
                            for (int i = 0; i < length; i++)
                            {
                                if (row[i].ToString().Contains('"'))
                                {
                                    row[i] = row[i].Replace('"', ' ');
                                }
                                dr[i] = Convert.ToString(row[i]);
                            }

                            dataTable.Rows.Add(dr);

                        }
                        else
                        {

                        }
                    }

                    counter++;
                }
            }
        }
        catch (Exception ex)
        {

        }

        return dataTable;
    }