c#操作Excel

來源:互聯網
上載者:User

標籤:eric   taf   mic   pat   .exe   null   state   style   varchar   

using System;using System.Collections.Generic;using System.Text;using System.Data.OleDb;using System.Data;namespace BizUpdate.Implement{    public class ExcelOperator    {        /// <summary>        /// 串連Excel        /// </summary>        /// <param name="filePath">資料庫地址</param>        public static OleDbConnection ExcelConnection(string filePath)        {            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;";            OleDbConnection odconn = new OleDbConnection(string.Format(connectionString, filePath));            return odconn;        }        /// <summary>        /// 從Excel中讀取資料        /// </summary>        /// <param name="filePath">Excel檔案</param>        /// <param name="selectQuery">SQL</param>        /// <returns></returns>        public static DataTable GetDataFromExcel(string filePath, string selectQuery)        {            OleDbConnection oconn = ExcelConnection(filePath);            try            {                if (oconn.State == ConnectionState.Closed)                { oconn.Open(); }                OleDbCommand odbc = oconn.CreateCommand();                odbc.CommandType = CommandType.Text;                odbc.CommandText = selectQuery;                OleDbDataAdapter da = new OleDbDataAdapter(odbc);                DataSet ds = new DataSet();                da.Fill(ds);                if (oconn.State != ConnectionState.Closed)                {                    oconn.Close();                }                foreach (DataRow dr in ds.Tables[0].Rows)                {                    foreach (DataColumn dc in ds.Tables[0].Columns)                    {                        if (dc.DataType == typeof(string))                        {                            if (dr[dc] == DBNull.Value)                            {                                dr[dc] = "";                            }                        }                    }                }                return ds.Tables[0];            }            catch (Exception ex)            {                throw ex;            }            finally            {                if (oconn.State != ConnectionState.Closed)                {                    oconn.Close();                }            }        }        /// <summary>        /// DataTabl寫入到Excel        /// </summary>        /// <param name="filePath"></param>        /// <param name="selectQuery"></param>        /// <returns></returns>        public static bool WriteDataToExcel(string filePath, DataTable dt, string TableName)        {            OleDbConnection oconn = ExcelConnection(filePath);            try            {                dt.TableName = TableName;                if (oconn.State == ConnectionState.Closed)                { oconn.Open(); }                OleDbCommand odbc = oconn.CreateCommand();                odbc.CommandType = CommandType.Text;                if(dt !=null && dt.Rows.Count > 0)                {                    string creSql = string.Format("CREATE TABLE {0} (",dt.TableName);                    for(int i = 0;i<dt.Columns.Count;i++)                    {                        if(i==dt.Columns.Count -1)                        {                           creSql += dt.Columns[i].ColumnName + " VARCHAR)";                        }                        else                        {                            creSql += dt.Columns[i].ColumnName + " VARCHAR,";                        }                    }                    odbc.CommandText = creSql;                    odbc.ExecuteNonQuery();                    foreach (DataRow row in dt.Rows)                    {                        string inSql = string.Format("insert into {0} values(", dt.TableName);                        for (int i = 0; i < dt.Columns.Count; i++)                        {                            if (i == dt.Columns.Count - 1)                            {                                inSql += "‘" + row[i].ToString() + "‘)";                            }                            else                            {                                inSql += "‘" + row[i].ToString() + "‘,";                            }                        }                        odbc.CommandText = inSql;                        odbc.ExecuteNonQuery();                    }                }                if (oconn.State != ConnectionState.Closed)                {                    oconn.Close();                }                return true;            }            catch (Exception ex)            {                return false;                throw new Exception("寫"+dt.TableName + "失敗"+ex.Message);            }            finally            {                if (oconn.State != ConnectionState.Closed)                {                    oconn.Close();                }            }        }    }}

 

c#操作Excel

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.