转---SQL与EXCEL交互(导出/导入)
生活随笔
收集整理的這篇文章主要介紹了
转---SQL与EXCEL交互(导出/导入)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
SQL與EXCEL交互(導(dǎo)出/導(dǎo)入)
EXCE->SQL
//方案一: 通過OleDB方式獲取Excel文件的數(shù)據(jù),然后通過DataSet中轉(zhuǎn)到SQL Server
openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel files(*.xls)|*.xls";
if(openFileDialog.ShowDialog()==DialogResult.OK)
{
???? FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
???? string filePath = fileInfo.FullName;
???? string connExcel = "rovider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0";
????
???? try
???? {
???????? OleDbConnection oleDbConnection = new OleDbConnection(connExcel);
???????? oleDbConnection.Open();
????????
???????? //獲取excel表
???????? DataTable dataTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
???????? //獲取sheet名,其中[0][1]...[N]: 按名稱排列的表單元素
???????? string tableName = dataTable.Rows[0][2].ToString().Trim();
???????? tableName = "[" + tableName.Replace("'","") + "]";
???????? //利用SQL語句從Excel文件里獲取數(shù)據(jù)
???????? //string query = "SELECT classDate,classPlace,classTeacher,classTitle,classID FROM " + tableName;
???????? string query = "SELECT 曰期,開課城市,講師,課程名稱,持續(xù)時間 FROM " + tableName;
???????? dataSet = new DataSet();
???????? //OleDbCommand oleCommand = new OleDbCommand(query, oleDbConnection);
???????? //OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCommand);
???????? OleDbDataAdapter oleAdapter = new OleDbDataAdapter(query,connExcel);
????????
???????? oleAdapter.Fill(dataSet,"gch_Class_Info");
???????? //dataGrid1.DataSource = dataSet;
???????? //dataGrid1.DataMember = tableName;
???????? dataGrid1.SetDataBinding(dataSet,"gch_Class_Info");
???????? //從excel文件獲得數(shù)據(jù)后,插入記錄到SQL Server的數(shù)據(jù)表
???????? DataTable dataTable1 = new DataTable();
????????
???????? SqlDataAdapter sqlDA1 = new SqlDataAdapter(@"SELECT classID, classDate,
classPlace, classTeacher, classTitle, durativeDate FROM gch_Class_Info",sqlConnection1);
????????
???????? SqlCommandBuilder sqlCB1 = new SqlCommandBuilder(sqlDA1);
????????
???????? sqlDA1.Fill(dataTable1);
???????? foreach(DataRow dataRow in dataSet.Tables["gch_Class_Info"].Rows)
???????? {
???????????? DataRow dataRow1 = dataTable1.NewRow();
????????????
???????????? dataRow1["classDate"] = dataRow["曰期"];
???????????? dataRow1["classPlace"] = dataRow["開課城市"];
???????????? dataRow1["classTeacher"] = dataRow["講師"];
???????????? dataRow1["classTitle"] = dataRow["課程名稱"];
???????????? dataRow1["durativeDate"] = dataRow["持續(xù)時間"];
???????????? dataTable1.Rows.Add(dataRow1);
???????? }
???????? Console.WriteLine("新插入 " + dataTable1.Rows.Count.ToString() + " 條記錄");
???????? sqlDA1.Update(dataTable1);
????????
???????? oleDbConnection.Close();
???? }
???? catch(Exception ex)
???? {
???????? Console.WriteLine(ex.ToString());
???? }
}
//方案二: 直接通過SQL語句執(zhí)行SQL Server的功能函數(shù)將Excel文件轉(zhuǎn)換到SQL Server數(shù)據(jù)庫
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel files(*.xls)|*.xls";
SqlConnection sqlConnection1 = null;
if(openFileDialog.ShowDialog()==DialogResult.OK)
{
???? string filePath = openFileDialog.FileName;
???? sqlConnection1 = new SqlConnection();
???? sqlConnection1.ConnectionString = "server=(local);integrated security=SSPI;initial catalog=Library";
???? //import excel into SQL Server 2000
???? /*string importSQL = "SELECT * into live41 FROM OpenDataSource" +
???????? "('Microsoft.Jet.OLEDB.4.0','Data Source=" + "\"" + "E:\\022n.xls" + "\"" +
???????? "; User ID=assword=; Extended properties=Excel 5.0')...[Sheet1$]";*/
???? //export SQL Server 2000 into excel
???? string exportSQL = @"EXEC master..xp_cmdshell
'bcp Library.dbo.live41 out " + filePath + "-c -q -S" + "\"" + "\"" +
???????? " -U" + "\"" + "\"" + " -P" + "\"" + "\"" + "\'";
????
???? try
???? {
???????? sqlConnection1.Open();
????????
???????? //SqlCommand sqlCommand1 = new SqlCommand();
???????? //sqlCommand1.Connection = sqlConnection1;
???????? //sqlCommand1.CommandText = importSQL;
???????? //sqlCommand1.ExecuteNonQuery();
???????? //MessageBox.Show("import finish!");
????????
???????? SqlCommand sqlCommand2 = new SqlCommand();
???????? sqlCommand2.Connection = sqlConnection1;
???????? sqlCommand2.CommandText = exportSQL;
???????? sqlCommand2.ExecuteNonQuery();
???????? MessageBox.Show("export finish!");
???? }
???? catch(Exception ex)
???? {
???????? MessageBox.Show(ex.ToString());
???? }
}
if(sqlConnection1!=null)
{
???? sqlConnection1.Close();
???? sqlConnection1 = null;
}
//方案三: 通過到入Excel的VBA dll,通過VBA接口獲取Excel數(shù)據(jù)到DataSet
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Excel files(*.xls)|*.xls";
ExcelIO excelio = new ExcelIO();
if(openFile.ShowDialog()==DialogResult.OK)
{
???? if(excelio!=null)
???????? excelio.Close();
???? excelio = new ExcelIO(openFile.FileName);
???? object[,] range = excelio.GetRange();
???? excelio.Close();
????
???? DataSet ds = new DataSet("xlsRange");
???? int x = range.GetLength(0);
???? int y = range.GetLength(1);
???? DataTable dt = new DataTable("xlsTable");
???? DataRow dr;
???? DataColumn dc;
????
???? ds.Tables.Add(dt);
???? for(int c=1; c<=y; c++)
???? {
???????? dc = new DataColumn();
???????? dt.Columns.Add(dc);
???? }
????
???? object[] temp = new object[y];
????
???? for(int i=1; i<=x; i++)
???? {
???????? dr = dt.NewRow();
???????? for(int j=1; j<=y; j++)
???????? {
???????????? temp[j-1] = range[i,j];
???????? }
????????
???????? dr.ItemArray = temp;
???????? ds.Tables[0].Rows.Add(dr);
???? }
???? dataGrid1.SetDataBinding(ds,"xlsTable");
????
???? if(excelio!=null)
???????? excelio.Close();
} SQL->EXCEL
???????? public class OPExcel
???????? {
???????????????? public OPExcel(){}
????????????????
???????????????? public bool WritDataSetToExcel(DataSet ds,string ExcelPath,ProgressBar pb)
???????????????? {
???????????????????????? if(ds==null)return false;
???????????????????????? int row=ds.Tables [0].Rows .Count ;
???????????????????????? int col=ds.Tables [0].Columns .Count ;
???????????????????????? if(row <1 || col<1)return false;
???????????????????????? pb.Minimum =0;pb.Maximum =row;pb.Value =0;
???????????????????????? Excel.ApplicationClass excel=new Excel.ApplicationClass ();
???????????????????????? try
???????????????????????? {????????
???????????????????????????????? excel.Workbooks.Add (Type.Missing );
???????????????????????????????? Excel.Worksheet sheet=(Excel.Worksheet)excel.ActiveSheet;
???????????????????????????????? for(int i=0;i<col;i++)
???????????????????????????????????????? sheet.Cells [1,i+1]=ds.Tables [0].Columns.ToString ();
???????????????????????????????? for(int i=0;i<row;i++)
???????????????????????????????? {
???????????????????????????????????????? Application.DoEvents ();
???????????????????????????????????????? for(int j=0;j<col;j++)
???????????????????????????????????????? {
???????????????????????????????????????????????? sheet.Cells [i+2,j+1]="'"+ds.Tables [0].Rows [j].ToString ();
???????????????????????????????????????? }
???????????????????????????????????????? pb.Value ++;
???????????????????????????????? }
???????????????????????????????? excel.Save (ExcelPath);
???????????????????????????????? excel.Quit ();
???????????????????????? }
???????????????????????? catch(System.Exception ex){MessageBox.Show (ex.Message );excel.Quit ();return false;}
???????????????????????? GC.Collect ();
???????????????????????? return true;
???????????????? }
???????? }
EXCE->SQL
//方案一: 通過OleDB方式獲取Excel文件的數(shù)據(jù),然后通過DataSet中轉(zhuǎn)到SQL Server
openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel files(*.xls)|*.xls";
if(openFileDialog.ShowDialog()==DialogResult.OK)
{
???? FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
???? string filePath = fileInfo.FullName;
???? string connExcel = "rovider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0";
????
???? try
???? {
???????? OleDbConnection oleDbConnection = new OleDbConnection(connExcel);
???????? oleDbConnection.Open();
????????
???????? //獲取excel表
???????? DataTable dataTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
???????? //獲取sheet名,其中[0][1]...[N]: 按名稱排列的表單元素
???????? string tableName = dataTable.Rows[0][2].ToString().Trim();
???????? tableName = "[" + tableName.Replace("'","") + "]";
???????? //利用SQL語句從Excel文件里獲取數(shù)據(jù)
???????? //string query = "SELECT classDate,classPlace,classTeacher,classTitle,classID FROM " + tableName;
???????? string query = "SELECT 曰期,開課城市,講師,課程名稱,持續(xù)時間 FROM " + tableName;
???????? dataSet = new DataSet();
???????? //OleDbCommand oleCommand = new OleDbCommand(query, oleDbConnection);
???????? //OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCommand);
???????? OleDbDataAdapter oleAdapter = new OleDbDataAdapter(query,connExcel);
????????
???????? oleAdapter.Fill(dataSet,"gch_Class_Info");
???????? //dataGrid1.DataSource = dataSet;
???????? //dataGrid1.DataMember = tableName;
???????? dataGrid1.SetDataBinding(dataSet,"gch_Class_Info");
???????? //從excel文件獲得數(shù)據(jù)后,插入記錄到SQL Server的數(shù)據(jù)表
???????? DataTable dataTable1 = new DataTable();
????????
???????? SqlDataAdapter sqlDA1 = new SqlDataAdapter(@"SELECT classID, classDate,
classPlace, classTeacher, classTitle, durativeDate FROM gch_Class_Info",sqlConnection1);
????????
???????? SqlCommandBuilder sqlCB1 = new SqlCommandBuilder(sqlDA1);
????????
???????? sqlDA1.Fill(dataTable1);
???????? foreach(DataRow dataRow in dataSet.Tables["gch_Class_Info"].Rows)
???????? {
???????????? DataRow dataRow1 = dataTable1.NewRow();
????????????
???????????? dataRow1["classDate"] = dataRow["曰期"];
???????????? dataRow1["classPlace"] = dataRow["開課城市"];
???????????? dataRow1["classTeacher"] = dataRow["講師"];
???????????? dataRow1["classTitle"] = dataRow["課程名稱"];
???????????? dataRow1["durativeDate"] = dataRow["持續(xù)時間"];
???????????? dataTable1.Rows.Add(dataRow1);
???????? }
???????? Console.WriteLine("新插入 " + dataTable1.Rows.Count.ToString() + " 條記錄");
???????? sqlDA1.Update(dataTable1);
????????
???????? oleDbConnection.Close();
???? }
???? catch(Exception ex)
???? {
???????? Console.WriteLine(ex.ToString());
???? }
}
//方案二: 直接通過SQL語句執(zhí)行SQL Server的功能函數(shù)將Excel文件轉(zhuǎn)換到SQL Server數(shù)據(jù)庫
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel files(*.xls)|*.xls";
SqlConnection sqlConnection1 = null;
if(openFileDialog.ShowDialog()==DialogResult.OK)
{
???? string filePath = openFileDialog.FileName;
???? sqlConnection1 = new SqlConnection();
???? sqlConnection1.ConnectionString = "server=(local);integrated security=SSPI;initial catalog=Library";
???? //import excel into SQL Server 2000
???? /*string importSQL = "SELECT * into live41 FROM OpenDataSource" +
???????? "('Microsoft.Jet.OLEDB.4.0','Data Source=" + "\"" + "E:\\022n.xls" + "\"" +
???????? "; User ID=assword=; Extended properties=Excel 5.0')...[Sheet1$]";*/
???? //export SQL Server 2000 into excel
???? string exportSQL = @"EXEC master..xp_cmdshell
'bcp Library.dbo.live41 out " + filePath + "-c -q -S" + "\"" + "\"" +
???????? " -U" + "\"" + "\"" + " -P" + "\"" + "\"" + "\'";
????
???? try
???? {
???????? sqlConnection1.Open();
????????
???????? //SqlCommand sqlCommand1 = new SqlCommand();
???????? //sqlCommand1.Connection = sqlConnection1;
???????? //sqlCommand1.CommandText = importSQL;
???????? //sqlCommand1.ExecuteNonQuery();
???????? //MessageBox.Show("import finish!");
????????
???????? SqlCommand sqlCommand2 = new SqlCommand();
???????? sqlCommand2.Connection = sqlConnection1;
???????? sqlCommand2.CommandText = exportSQL;
???????? sqlCommand2.ExecuteNonQuery();
???????? MessageBox.Show("export finish!");
???? }
???? catch(Exception ex)
???? {
???????? MessageBox.Show(ex.ToString());
???? }
}
if(sqlConnection1!=null)
{
???? sqlConnection1.Close();
???? sqlConnection1 = null;
}
//方案三: 通過到入Excel的VBA dll,通過VBA接口獲取Excel數(shù)據(jù)到DataSet
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Excel files(*.xls)|*.xls";
ExcelIO excelio = new ExcelIO();
if(openFile.ShowDialog()==DialogResult.OK)
{
???? if(excelio!=null)
???????? excelio.Close();
???? excelio = new ExcelIO(openFile.FileName);
???? object[,] range = excelio.GetRange();
???? excelio.Close();
????
???? DataSet ds = new DataSet("xlsRange");
???? int x = range.GetLength(0);
???? int y = range.GetLength(1);
???? DataTable dt = new DataTable("xlsTable");
???? DataRow dr;
???? DataColumn dc;
????
???? ds.Tables.Add(dt);
???? for(int c=1; c<=y; c++)
???? {
???????? dc = new DataColumn();
???????? dt.Columns.Add(dc);
???? }
????
???? object[] temp = new object[y];
????
???? for(int i=1; i<=x; i++)
???? {
???????? dr = dt.NewRow();
???????? for(int j=1; j<=y; j++)
???????? {
???????????? temp[j-1] = range[i,j];
???????? }
????????
???????? dr.ItemArray = temp;
???????? ds.Tables[0].Rows.Add(dr);
???? }
???? dataGrid1.SetDataBinding(ds,"xlsTable");
????
???? if(excelio!=null)
???????? excelio.Close();
} SQL->EXCEL
???????? public class OPExcel
???????? {
???????????????? public OPExcel(){}
????????????????
???????????????? public bool WritDataSetToExcel(DataSet ds,string ExcelPath,ProgressBar pb)
???????????????? {
???????????????????????? if(ds==null)return false;
???????????????????????? int row=ds.Tables [0].Rows .Count ;
???????????????????????? int col=ds.Tables [0].Columns .Count ;
???????????????????????? if(row <1 || col<1)return false;
???????????????????????? pb.Minimum =0;pb.Maximum =row;pb.Value =0;
???????????????????????? Excel.ApplicationClass excel=new Excel.ApplicationClass ();
???????????????????????? try
???????????????????????? {????????
???????????????????????????????? excel.Workbooks.Add (Type.Missing );
???????????????????????????????? Excel.Worksheet sheet=(Excel.Worksheet)excel.ActiveSheet;
???????????????????????????????? for(int i=0;i<col;i++)
???????????????????????????????????????? sheet.Cells [1,i+1]=ds.Tables [0].Columns.ToString ();
???????????????????????????????? for(int i=0;i<row;i++)
???????????????????????????????? {
???????????????????????????????????????? Application.DoEvents ();
???????????????????????????????????????? for(int j=0;j<col;j++)
???????????????????????????????????????? {
???????????????????????????????????????????????? sheet.Cells [i+2,j+1]="'"+ds.Tables [0].Rows [j].ToString ();
???????????????????????????????????????? }
???????????????????????????????????????? pb.Value ++;
???????????????????????????????? }
???????????????????????????????? excel.Save (ExcelPath);
???????????????????????????????? excel.Quit ();
???????????????????????? }
???????????????????????? catch(System.Exception ex){MessageBox.Show (ex.Message );excel.Quit ();return false;}
???????????????????????? GC.Collect ();
???????????????????????? return true;
???????????????? }
???????? }
總結(jié)
以上是生活随笔為你收集整理的转---SQL与EXCEL交互(导出/导入)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 奥运开幕了 您给开幕式和火炬点火仪式打几
- 下一篇: 使用Maven Archetype生成工