【发布时间】:2018-03-19 07:11:00
【问题描述】:
string fpath;
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
ofd.Title = "Select an excel file";
ofd.Filter = "Excel Files | *.xls";
if (ofd.ShowDialog() == DialogResult.OK)
{
fpath = ofd.FileName;
DataTable dt = new DataTable();
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source="+ fpath +"; Extended Properties='Excel 8.0; HDR=YES'"))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(@"SELECT * FROM [Sheet1$]",conn))
{
using (OleDbDataAdapter oda = new OleDbDataAdapter(cmd))
{
oda.SelectCommand = cmd;
oda.Fill(dt);
}
}
conn.Close();
}
if (dt != null)
{
using (SqlConnection conn = new SqlConnection(@"Data Source=(local);
Initial Catalog=inventory;
Integrated Security=True"))
{
conn.Open();
using (SqlBulkCopy sbc = new SqlBulkCopy(conn))
{
sbc.DestinationTableName = "dbo.product";
sbc.ColumnMappings.Add("Item", "Item");
sbc.ColumnMappings.Add("Brand", "Brand");
sbc.ColumnMappings.Add("Part", "Part");
sbc.ColumnMappings.Add("Description", "Description");
sbc.ColumnMappings.Add("Manufacturer", "Manufacturer");
sbc.ColumnMappings.Add("Car", "Car");
sbc.ColumnMappings.Add("Year", "Year");
sbc.ColumnMappings.Add("Price", "Price");
sbc.WriteToServer(dt);
MessageBox.Show("Import Successfull.", "Import Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
conn.Close();
}
}
}
}
上面的代码让用户上传一个excel文件(97-2003格式)要复制到sql数据库。问题是如何检查数据库中是否已经存在excel数据?
excel文件与sql数据库的列名相同。
【问题讨论】:
标签: c# sql sql-server excel database