C#实现Access导入导出Excel
生活随笔
收集整理的這篇文章主要介紹了
C#实现Access导入导出Excel
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、Access從Excel中導入數據
1.用到的Excel表的格式及內容實現[c-sharp] view plaincopyprint?OleDbConnection con = new OleDbConnection(); try { OpenFileDialog openFile = new OpenFileDialog();//打開文件對話框。 openFile.Filter = ("Excel 文件(*.xls)|*.xls");//后綴名。 if (openFile.ShowDialog() == DialogResult.OK) { string filename = openFile.FileName; int index = filename.LastIndexOf("//");//截取文件的名字 filename = filename.Substring(index + 1); conExcel.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + Application.StartupPath + "//Appdata.mdb"; //將excel導入access //distinct :刪除excel重復的行. //[excel名].[sheet名] 已有的excel的表要加$ //where not in : 插入不重復的記錄。 string sql = "insert into Users2(用戶編號,用戶姓名) select distinct * from [Excel 8.0;database=" + filename + "].[name$] where 用戶編號 not in (select 用戶編號 from Users2) "; OleDbCommand com = new OleDbCommand(sql, con); con.Open(); com.ExecuteNonQuery(); MessageBox.Show("導入數據成功", "導入數據", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { con.Close(); } 二、Access導出Excel
[c-sharp] view plaincopyprint?OleDbConnection con = new OleDbConnection(); try { SaveFileDialog saveFile = new SaveFileDialog(); saveFile.Filter = ("Excel 文件(*.xls)|*.xls");//指定文件后綴名為Excel 文件。 if (saveFile.ShowDialog() == DialogResult.OK) { string filename = saveFile.FileName; if (System.IO.File.Exists(filename)) { System.IO.File.Delete(filename);//如果文件存在刪除文件。
} int index = filename.LastIndexOf("//");//獲取最后一個/的索引 filename = filename.Substring(index + 1);//獲取excel名稱(新建表的路徑相對于SaveFileDialog的路徑) //select * into 建立 新的表。 //[[Excel 8.0;database= excel名].[sheet名] 如果是新建sheet表不能加$,如果向sheet里插入數據要加$. //sheet最多存儲65535條數據。 string sql = "select top 65535 * into [Excel 8.0;database=" + filename + "].[用戶信息] from Users2"; con.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + Application.StartupPath + "//Appdata.mdb";//將數據庫放到debug目錄下。 OleDbCommand com = new OleDbCommand(sql, con); con.Open(); com.ExecuteNonQuery(); MessageBox.Show("導出數據成功", "導出數據", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { con.Close(); }
?
總結
以上是生活随笔為你收集整理的C#实现Access导入导出Excel的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js实现php中sleep()延时的功能
- 下一篇: c# char unsigned_dll