您的位置:首页 > 数据库

把excel表格数据导入到SqlServer

2010-09-11 15:04 746 查看
1. 读取excel表数据
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Excel Worksheets|*.xls";
if (open.ShowDialog() == DialogResult.OK)
{
this.txtBrowser.Text = open.FileName;
//连接串
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + open.FileName + ";Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
//返回Excel的架构,包括各个sheet表的名称,类型,创建时间和修改时间等 
DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
//包含excel中表名的字符串数组,可解决查找不到sheet表的问题
string[] strTableNames = new string[dtSheetName.Rows.Count];
for (int k = 0; k < dtSheetName.Rows.Count; k++)
{
strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
}
OleDbDataAdapter myCommand = null;
DataTable dgvCustomerInfo = new DataTable();
//从指定的表明查询数据,可先把所有表明列出来供用户选择
string strExcel = "select * from [" + strTableNames[0] + "]";
myCommand = new OleDbDataAdapter(strExcel, connectionString);
dgvCustomerInfo = new DataTable();
myCommand.Fill(dgvCustomerInfo);

this.dgvExcelInfo.DataSource = dgvCustomerInfo;
}

2. 导入SqlServer数据库
//本地连接字符串
string ConnectionString = ConfigurationManager.AppSettings["ConnectionString"];

using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();

string sqlstr = string.Empty;
for (int i = 0; i < this.dgvExcelInfo.Rows.Count; i++)
{
if (this.dgvExcelInfo.Rows[i].Cells["顧客NO#"].Value.ToString().Trim() == string.Empty)
{
continue;
}
string tempCustomerID = this.dgvExcelInfo.Rows[i].Cells["顧客NO#"].Value.ToString().Trim();
sqlstr += " UPDATE CustomerMst SET " + updateSqlConcat(this.dgvExcelInfo.Rows[i]) + " WHERE CustomerID=" + tempCustomerID;
}

SqlCommand command = new SqlCommand(sqlstr, conn);
command.ExecuteNonQuery();

SqlDataAdapter sa = new SqlDataAdapter("SELECT * FROM CustomerMst cm", conn);
DataTable dtSql = new DataTable();
sa.Fill(dtSql);
this.dgvCustomerInfo.DataSource = dtSql;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: