【问题标题】:Create table based on columns from a CSV file [closed]根据 CSV 文件中的列创建表 [关闭]
【发布时间】:2014-06-10 15:35:39
【问题描述】:

我有基于文件列(DBF、Excel)创建新表的现有代码:

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 文件中的每一行并获取每一行的字段并将其添加到列表数组中:

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 文件
  • 根据第一行计数(即文件头)创建 SQL 表

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

这个网站有什么帮助吗:CSV to SQL

【问题讨论】:

  • 警告您的代码容易受到 sql 注入攻击!

标签: c# sql sql-server excel csv


【解决方案1】:

您不需要在第二个代码 sn-p 中展开所有列名。读取文件后,您可以对字符串使用 split 命令将标题行拆分为列表(只需使用索引访问文件的第一行)。然后,一旦有了列名列表,就可以使用 foreach 循环遍历它们,并以与上述代码中相同的方式创建表。只需替换您的字符串项的数据列。

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

我希望这会有所帮助,代码可能并不完全正确,但应该能让您了解您需要什么。

【讨论】:

  • 我收到以下错误:Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable&lt;string&gt;'
  • 好的,所以你需要 'var lines = File.ReadLines(textBox1.Text); List readHeader = lines.ElementAt(0).Split(',').ToList();'
猜你喜欢
  • 2023-03-26
  • 2021-04-09
  • 2020-03-26
  • 1970-01-01
  • 2021-12-17
  • 2022-01-17
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多