【问题提问、论坛交流】前几天,一直在网上搜索资料,想实现这个功能,都没找到我想要的结果,最后只要自己想办法实现了。
大体思路是:将EXCEL的数据提出放在数据集中,在过循环将主表数据插入,在通过循环将从表插入:
代码如下:
private void button1_Click(object sender, System.EventArgs e)
{
//选择文件
ofdSelectExcel.Filter = "Excel Files(*.xls)|*.xls";
ofdSelectExcel.RestoreDirectory = true;
if( ofdSelectExcel.ShowDialog() == DialogResult.OK )
{
if ( ofdSelectExcel.FileName.Trim().Length == 0)
{
MessageBox.Show(this,"Please select a excel file first!");
return;
}
else
{
ImportExcelToSqlServer(ofdSelectExcel.FileName.Trim());
}
}
}
********************************************************
提取数据
public void ImportExcelToSqlServer(string fileName)
{
if (fileName == null)
{
throw new ArgumentNullException("filename string is null!");
}
if (fileName.Length == 0)
{
throw new ArgumentException("filename string is empty!");
}
string oleDBConnString = String.Empty;
oleDBConnString = "Provider=Microsoft.Jet.OLEDB.4.0;";
oleDBConnString += "Data Source=";
oleDBConnString += fileName;
oleDBConnString += ";Extended Properties=Excel 8.0;";
OleDbConnection oleDBConn = null;
OleDbDataAdapter oleAdMaster = null;
DataTable m_tableName=new DataTable();;
DataSet ds=new DataSet();
try
{
oleDBConn = new OleDbConnection(oleDBConnString);
oleDBConn.Open();
m_tableName=oleDBConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,null);
if (m_tableName != null && m_tableName.Rows.Count > 0)
{
m_tableName.TableName =m_tableName.Rows[0]["TABLE_NAME"].ToString();
}
string sqlMaster;
sqlMaster=" SELECT * FROM ["+m_tableName+"]";
oleAdMaster=new OleDbDataAdapter(sqlMaster,oleDBConn);
oleAdMaster.Fill(ds,"m_tableName");
MailRebateManager manger=new MailRebateManager();
bool isSucess=manger.AddExceLGmailRebate(ds.Tables["m_tableName"],ApplicationVariable.HomeCompanyID);
if(isSucess)
{
MessageBox.Show("Manipulate Succs!");
}
else
{
MessageBox.Show("Manipulate Failed");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
SimpleLogger.Log(ex);
编辑:xker.com