【发布时间】:2017-09-30 10:32:47
【问题描述】:
我想从 Excel 工作表中导入特定列并插入到 SQL Server 表中的特定列中。
下面的代码没有向表中插入任何数据,我认为是因为主键是它在网格视图中成功显示数据但没有插入数据,所以我想插入一列而不是整个表:
protected void ImportButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
string FilePath = Server.MapPath(FolderPath + FileName);
FileUpload1.SaveAs(FilePath);
Import_To_Grid(FilePath);
}
}
private void Import_To_Grid(string FilePath)
{
string conStr = "";
//switch (Extension)
//{
// case ".xls": //Excel 97-03
// conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"]
// .ConnectionString;
// break;
// case ".xlsx": //Excel 07
// conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"]
// .ConnectionString;
// break;
//}
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", FilePath);
conStr = String.Format(excelConnString, FilePath);
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmdExcel.Connection = connExcel;
//Get the name of First Sheet
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
//Read Data from First Sheet
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
using (OleDbDataReader dReader = cmdExcel.ExecuteReader())
{
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(_Conn.ConnStr()))
{
//Set your Destination table name
sqlBulk.DestinationTableName = "[AIS].[Inventory].[Inventory_Movments_TBL]";
sqlBulk.WriteToServer(dt);
//Bind Data to GridView
GridView1.Caption = Path.GetFileName(FilePath);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
connExcel.Close();
}
【问题讨论】:
标签: c# asp.net sql-server excel