Import csv file into SQL Server database in C# Windows application without header

后端 未结 2 947
小蘑菇
小蘑菇 2021-01-26 04:46

I am trying to import a .csv file into a SQL Server database without the headers.

This code works fine, but with headers - how can skip the headers? What do

相关标签:
2条回答
  • 2021-01-26 04:54

    Just ignore the headers when you read the data from the file. Delete these lines:

    string[] headerColumns = header.Split(',');
    
    foreach (string headerColumn in headerColumns)
    {
        importedData.Columns.Add(headerColumn);
    }
    
    0 讨论(0)
  • 2021-01-26 04:56

    Can you remove the columns and use index instead? Of course, you'd need to know the position of each field within a file.

     string line = "001,0000002226,01,2011/03/27,07:07,";
    
            DataTable importedData = new DataTable();
    
    
            DataRow importedRow = importedData.NewRow();
    
            string[] fields = line.Split(',');
            for (int i = 0; i < fields.Count(); i++)
            {
    
                importedRow[i] = fields[i];
    
            }
    
            using (SqlConnection conn = new SqlConnection("Data Source=HAIDER-PC\\SQLEXPRESS;Initial Catalog=mydatabase;Integrated Security=True"))
            {
                conn.Open();
                foreach (DataRow importRow in importedData.Rows)
                {
    
                    SqlCommand cmd = new SqlCommand("INSERT INTO imported_data (device_id,employee_id,status,date,time ) " +
                                                      "VALUES (@device_id,@employee_id,@status,@date,@time)", conn);
                    cmd.Parameters.AddWithValue("@device_id", importRow[0]);
                    cmd.Parameters.AddWithValue("@employee_id", importRow[1]);
                    cmd.Parameters.AddWithValue("@status", importRow[2]);
                    cmd.Parameters.AddWithValue("@date", importRow[4]);
                    cmd.Parameters.AddWithValue("@time", importRow[5]);
                    cmd.ExecuteNonQuery();
                }
    
            }
    
    0 讨论(0)
提交回复
热议问题