根据CSV文件中的列创build表

我有现有的代码,基于文件(DBF,Excel)的列创build一个新的表格:

OleDbConnection oConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + tbXLSBrowse.Text + "';Extended Properties=\"Excel 12.0 xml;HDR=Yes;IMEX=1\""); OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", oConn); //change to the sheet name oConn.Open(); DataTable dt = new DataTable(); dt.Load(command.ExecuteReader()); oConn.Close(); DataTableReader reader = dt.CreateDataReader(); myConnection = new SqlConnection(cString); myConnection.Open(); // checking whether the table selected from the dataset exists in the database or not string exists = null; try { SqlCommand cmd = new SqlCommand("SELECT * FROM sysobjects where name = '" + tb.Text + "'", myConnection); exists = cmd.ExecuteScalar().ToString(); //MessageBox.Show("EXISTS"); } catch (Exception exce) { exists = null; //MessageBox.Show("DOESNT EXIST"); } if (exists == null) { // selecting each column of the datatable to create a table in the database foreach (DataColumn dc in dt.Columns) { if (exists == null) { SqlCommand createtable = new SqlCommand("CREATE TABLE " + tb.Text + " (" + dc.ColumnName + " varchar(MAX))", myConnection); createtable.ExecuteNonQuery(); exists = tbXLSTableName.Text; } else { SqlCommand addcolumn = new SqlCommand("ALTER TABLE " + tb.Text + " ADD [" + dc.ColumnName + "] varchar(MAX)", myConnection); addcolumn.ExecuteNonQuery(); } } } 

文本框如下:

 //tbXLSBrowse.Text = the excel file name; //tb.Text = user generated table name; 

上面的代码是Excel文件的一个例子。 我有一个CSV,我也试图做同样的,但不知道如何做到这一点。

我有以下代码,它读取CSV文件中的每一行,并获取每行的字段,并将其添加到List数组:

 var lines = File.ReadLines(textBox1.Text); List<string> colArray = new List<string>(); foreach (string line in lines) //for each line { using (TextFieldParser parser = new TextFieldParser(textBox1.Text)) { parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters(","); while (!parser.EndOfData) //while file is being read { string[] fields = parser.ReadFields(); foreach (string field in fields) //for each column { colArray.Add(field); colArray.ToArray(); } MessageBox.Show(colArray.Count + ""); //displays the count for the columns for each line colArray.Clear(); //clear the column to use it for next line } } } 

我怎样才能把上面的代码发布到上面的代码来完成以下工作:

  • 阅读CSV文件
  • 根据第一行数(这是文件的头)创build一个SQL表

或者是不可能的? 我想这样做的原因是因为每行有329列,如果我能够用代码来完成这一点,从长远来看将节省大量的时间。

这个网站会有什么帮助: CSV到SQL

您不需要展开第二个代码段中的所有列名称。 一旦读取了文件,您可以使用split命令将string拆分成一个列表(只需使用索引访问文件的第一行)。 然后,一旦你有一个列名称的列表,你可以通过使用foreach循环遍历它们,并以上述代码中的相同方式创build表格。 只需replace您的string项目的datacolumn。

 var lines = File.ReadLines(textBox1.Text); List<string> headerRow = lines.ElementAt(0).Split(',').ToList(); foreach (string header in headerRow) { Create table etc....... } 

我希望这有助于,代码可能不完全正确,但应该给你一个你需要什么的想法。