如何使用c#将Excel工作表数据保存到数据表
问题描述:
我需要将excel表数据保存到数据表
任何人都可以帮我这个怎么办?
谢谢
John
Hi,
I need to save the excel sheet data to data table
Can any one help me how can I do this?
Thanks
John
答
您可以轻松搜索互联网并找到无数的例子,所以我认为它现在必须被打破。幸运的是,我碰巧有一个链接可以帮助它恢复运行。
点击我! [ ^ ]
You could have easily searched the internet and found countless examples of this, so I presume it must be broken right now. Fortunately I just happen to have a link that will help if it gets back up and running.
Click me![^]
您可以使用以下方法将xls数据插入数据库。
You can use the below approach for inserting xls data into database.
if (openFileDialog.ShowDialog(this) == DialogResult.OK)
{
path = openFileDialog.InitialDirectory + openFileDialog.FileName;
}
string constring = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + path + "; Extended Properties=Excel 12.0 Xml";
OleDbConnection con = new OleDbConnection(constring);
try
{
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String[] excelSheets = new String[dt.Rows.Count];
i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
for (int j = 0; j < excelSheets.Length; j++)
{
string query = "SELECT * FROM [" +excelSheets[j]+ "]; ";
OleDbDataAdapter adp = new OleDbDataAdapter(query, constring);
DataSet ds = new DataSet();
string hCode = string.Empty;
string description = string.Empty;
adp.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
hCode = Convert.ToString(dr[1]);
description = Convert.ToString(dr[2]);
if (!(string.IsNullOrEmpty(hCode) && string.IsNullOrEmpty(description)))
{
dboject.InsertSiteNameIntoDatabase(hCode, description);
}
}
}
lblDisplay.Text = "Inserted successfully";
}
catch (Exception ex)
{
dboject.VMSLog(ex.Message);
}
finally
{
con.Close();
}