日期:2014-05-17  浏览次数:21069 次

c#实现excel表数据导入到sql数据库指定表中
我现在有数据库A,数据库A内有已建好的表B,我想用C#实现excel表数据导入到数据库A中指定的表B中,这个如何实现?最好有代码加注释。谢谢

------解决方案--------------------
基本数据库操作,连接数据库A,然后引用office的dll去操作excel,读取每个格的内容,insert到数据库,如果你不会操作数据库,参考http://www.cnblogs.com/dongdonghuihui/archive/2009/08/13/1545446.html
excel参考http://www.cnblogs.com/MR_ke/archive/2010/03/02/1676210.html
------解决方案--------------------
刚做了这个内容,也贴下代码:

//string srcPath = System.Windows.Forms.Application.StartupPath + @"\UserInfo.xls";
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + srcPath + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
DataTable xlsTable = new DataTable();

strExcel = "select * from [sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
myCommand.Fill(xlsTable);
conn.Close();

//1、删除TB_TEMP表中的数据
sql.DeleteTbTemp();

//2、把xlsTable数据写入到TB_TEMP中。
try
{
using (OleDbConnection connection = new OleDbConnection(ConfigurationManager.ConnectionStrings["HZZP_JT2012"].ConnectionString))
{
connection.Open();
DataSet ds = new DataSet();

OleDbCommand command = new OleDbCommand("SELECT * FROM TB_TEMP", connection);
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.SelectCommand = command;
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.InsertCommand = builder.GetInsertCommand();
adapter.DeleteCommand = builder.GetDeleteCommand();
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.Fill(ds, "TB_TEMP");

DataRow[] rows = xlsTable.Select();
foreach (DataRow row in rows)
{
int user_id;
if (int.TryParse(row["USER_ID"].ToString(), out user_id))
{
ds.Tables[0].Rows.Add(new object[] { row["USER_ID"], row["USER_NAME"], row["PHONE"], row["VILLAGE"], row["ADDRESS"], row["USER_MEMO"] });
}

try
{
if (ds.HasChanges())
{
adapter.Update(ds, "TB_TEMP");
}
}
catch (Exception err)
{
MessageBox.Show(this, err.Message, "保存失败!", MessageBoxButtons.OK);
}
connection.Close(); 
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
------解决方案--------------------

曾经写的代码
C# code


        private void importAttachToSQl()
        {
            int rowsAffected = 0;
            string updateStr = "";
            string cmd ="Select " + sqlColumnsForImport + " from " + sqlTableName;
            DataTable thisDataTable = new DataTable();
            tr