【发布时间】: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