OLEDB操作EXCEL

OLEDB對EXCEL進行增刪改查

       Microsoft.Office.Interop.Excel.ApplicationClass 將DataTable中的數據插入EXCEL

        /// <summary>
        /// 將DataSet裏所有數據導入Excel.
        /// 需要添加COM: Microsoft Excel Object Library.
        /// using Excel;
        /// </summary>
        /// <param name="filePath">Excel文件的路徑</param>
        /// <param name="ds">到導入Excel的數據源</param>
        private void ExportToExcel(string filePath, DataSet ds)
        {
            object oMissing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.ApplicationClass xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            try
            {
                //打開EXCEL文件
                Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filePath, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
                // Excel.Workbook xlWorkbook=xlApp.Workbooks.只有Open屬性,沒有Write屬性
                Microsoft.Office.Interop.Excel.Worksheet xlWorksheet;
                //循環所有DataTable
                for (int i = 0; i < ds.Tables.Count; i++)
                {
                    //添加入一個新的Sheel頁
                    xlWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkbook.Worksheets.Add(oMissing, oMissing, 1, oMissing);
                    //以TableName作爲新加的sheel頁名
                    xlWorksheet.Name = ds.Tables[i].TableName;
                    //取出這個DataTable中的所有值,暫時存於stringBuffer中
                    StringBuilder stringBuffer =new StringBuilder();
                   
                    for (int j = 0; j < ds.Tables[i].Rows.Count; j++)
                    {
                        for (int k = 0; k < ds.Tables[i].Columns.Count; k++)
                        {
                            stringBuffer.Append( ds.Tables[i].Rows[j][k].ToString());
                            if (k < ds.Tables[i].Columns.Count - 1)
                                stringBuffer.Append("\t");
                        }
                        stringBuffer.Append("\n");
                    }
                    //利用系統剪貼板
                    System.Windows.Forms.Clipboard.SetDataObject("");
                    //將stringBuffer放入剪貼板
                    System.Windows.Forms.Clipboard.SetDataObject(stringBuffer);
                    //選中這個sheel頁中的第一個單元格
                    ((Excel.Range)xlWorksheet.Cells[1, 1]).Select();
                    //粘貼
                    xlWorksheet.Paste(oMissing, oMissing);
                    //清空系統剪貼板
                    System.Windows.Forms.Clipboard.SetDataObject("");
                }
                //保存並關閉這個工作薄
                xlWorkbook.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlSaveChanges, oMissing, oMissing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook);
                xlWorkbook = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                //釋放...
                xlApp.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
                xlApp = null;
                GC.Collect();
            }
        }

       

        OleDbConnection connection;

        //打開數據庫連接
        public void OpenConnection(string xlsFils) {
            if (!File.Exists(xlsFils))
            {
                MessageBox.Show("文件\"" + xlsFils + "\"不存在", "提示");

                return;
            }
            string conn = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + xlsFils + ";Extended Properties='Excel 8.0;HDR=no;IMEX=0'";
            connection = new OleDbConnection(conn);
            connection.Open();
        }

        //查詢數據
        public DataTable Select()
        {
            DataTable dt = new DataTable();
            string Sql = "select * from [Sheet1$]";
            OleDbDataAdapter mycommand = new OleDbDataAdapter(Sql, connection);
            mycommand.Fill(dt);
            return dt;
        }
         

        private void Form1_Load(object sender, EventArgs e)
        {
            string xlsFile = System.Windows.Forms.Application.StartupPath + "/" + "ExcelFiles/test.xls";
            OpenConnection(xlsFile);
        }

        //插入數據
        public void Insert()
        {
            string sql = string.Format("insert into [Sheet1$] values('{0}','{1}','{2}')", "陳太漢", "陳曉玲", "520");
            OleDbCommand myCommand = new OleDbCommand(sql, connection);
            myCommand.ExecuteNonQuery();
            Select();
        }

        private void btAdd_Click(object sender, EventArgs e)
        {
            Insert();
        }

        //Excel不支持SQl語句的方式進行刪除,可以用把每個字段的值設爲空的方式進行刪除
        public void Delete()
        {
            string sql = string.Format("Update [Sheet1$] set col1=NULL,col2=NULL,col3=NULL where col1='{0}'", "陳太漢");
            OleDbCommand myCommand = new OleDbCommand(sql, connection);
            myCommand.ExecuteNonQuery();
            Select();
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            Delete();
        }

        //更新數據
        private new void Update() {
            string sql = string.Format("update  [Sheet1$] set col1='{0}' where col1='{1}'", "陳曉玲","陳太漢");
            OleDbCommand myCommand = new OleDbCommand(sql, connection);
            myCommand.ExecuteNonQuery();
            Select();
        }
        private void btUpdate_Click(object sender, EventArgs e)
        {
            Update();
        }

        private void btSelect_Click(object sender, EventArgs e)
        {
            Select();

        }

注:1)使用 Excel 工作簿時,默認情況下,區域中的第一行是標題行(或字段名稱)。如果第一個區域不包含標題,您可以在連接字符串的擴展屬性中指定 HDR=NO。如果您在連接字符串中指定 HDR=NO,Jet OLE DB 提供程序將自動爲您命名字段(不管excel中的列叫什麼名字,F1 表示第一個字段,F2 表示第二個字段,依此類推,select F1,F2 from [sheet1$]);

2)IMEX=1將所有讀入數據看作字符,其他值(0、2)請查閱相關幫助文檔;

3)如果出現“找不到可安裝的isam”錯誤,一般是連接字符串錯誤

DoOleSql(sql,"test.xls");

6、刪除excel文件中的數據:不提倡使用這種方法

7、對於非標準結構的excel表格,可以指定excel中sheet的範圍

1)讀取數據:string sql = "select * from [sheet1$A3:F20]";

2)更新數據:string sql = "update [sheet1$A9:F15] set FieldName='333' where AnotherFieldName='b3'";

3)插入數據:string sql = "insert into [sheet1$A9:F15](FieldName1,FieldName2,…) values('a',’b’,…)";

2003和2007的鏈接區別

//string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + excelFile + ";Extended Properties='Excel 8.0; HDR=NO; IMEX=1'"; //此連接只能操作Excel2007之前(.xls)文件

string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + excelFile + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'"; //此連接可以操作.xls與.xlsx文件

//獲取excel中都有哪些sheet

dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章