用c#讀取Excel的方法

一、
在工程中加入相關的Com組件
代碼示例:
   ExcelObj=new Excel.Application();
    object missing=Type.Missing;
    Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(
     this.textBoxExcelName.Text, missing, missing, missing,
     missing, missing, missing, missing, missing, missing, missing,
     missing,missing);
    Excel.Sheets sheets = theWorkbook.Worksheets;
    Excel.Worksheet datasheet=null;
    foreach(Excel.Worksheet sheet in sheets)
    {
     if(sheet.Name==textBoxSheetName.Text)
     {
      datasheet=sheet;
      break;
     }
    }
    if(null==datasheet)
    {
     MessageBox.Show(this,"沒有名稱爲"+textBoxSheetName+"的Sheet.");
     return;
    }
    if(""==this.textBoxCellFrom.Text||""==this.textBoxCellTo.Text)
    {
     MessageBox.Show(this,"請輸入編號起始單元格。");
     return;
    }
    Excel.Range range=datasheet.get_Range(this.textBoxCellFrom.Text,this.textBoxCellTo.Text);
    System.Array myvalues = (System.Array)(range.Cells.Value);//如果只有一個格(cellfrom==cellto)轉成object即可.
    string[] codes=new string[myvalues.Length];
    int i=0;
    for (i = 1; i <= myvalues.Length; i++)
    {
     if (myvalues.GetValue(i, 1) == null)
      codes = "";
     else
      codes = (string)myvalues.GetValue(i, 1).ToString();
    }
二、經常需要在數據庫與Execl之間互導數據。net時代,ADO.NET可以使用使用Microsoft.Jet.OleDb訪問訪問Excel,網上已經有很多類似的資源,最典型也是最簡單的可能如下:(asp.net環境)
/// <summary>
        /// 獲取Excel文件的Sheet1的名字
        /// </summary>
        /// <param name="strExcelFileName">Excel文件名(帶全路徑)</param>
        /// <returns>Sheet1的名字</returns>
        public static string getSheetName(string strExcelFileName)
        {
            Excel.Application app = null;
            string name;
            try
            {
                app = new ApplicationClass();
                app.Workbooks.Open(strExcelFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                Sheets sheets = app.Worksheets;
                if ((sheets != null)
                    && (sheets.Count > 0))
                {
                    name = ((Excel._Worksheet)sheets.get_Item(1)).Name;
                }
                else
                {
                    name = "";
                }
            }
            catch (Exception ef)
            {
                name = "";
            }
            finally
            {
                if ((app != null)
                    && (app.Workbooks != null))
                {
                    app.Workbooks.Close();
                }
            }
            return name;
        }

        /// <summary>
        /// 讀取Excel文件中Sheet1的內容
        /// </summary>
        /// <param name="fileName">Excel文件名</param>
        /// <returns>DataTable</returns>
        public static System.Data.DataTable getExcelSheetData(string fileName)
        {
            //  OLEDB字串
            string strConn = getConnStr(fileName);

            
            OleDbConnection conn=null;
            string name = "";
            try
            {
                
                //連接數據源
                conn = new OleDbConnection(strConn);

                conn.Open();
                System.Data.DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if ((dt != null)
                    && (dt.Rows != null)
                    && (dt.Rows.Count > 0)
                    && (dt.Columns != null)
                    && (dt.Columns.Count > 2))
                {
                    name = dt.Rows[0][2].ToString();
                    if ((name == null)
                        || (name.Equals("")))
                    {
                        throw new Exception("Sheet Name NULL!");
                    }
                }
                else
                {
                    throw new Exception("Get Sheet Name Error!");
                }
                
                string sql = string.Format("select * from [{0}]", name);  //Sql語句
                
                DataSet ds = new DataSet(); //定義存放的數據表
              
                OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn); //適配到數據源

                adapter.Fill(ds);

                if ((ds != null)
                    && (ds.Tables != null)
                    && (ds.Tables.Count > 0))
                {
                    return ds.Tables[0];
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ef)
            {
                throw ef;
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
        }


        public  static bool FileExists(string fileName, string type)
        {
            try
            {
                if ((type == null)
                    || (type.Equals("")))
                {
                    type = ".xls";
                }
                if ((fileName != null)
                    && (!fileName.Equals("")))
                {
                    if (!fileName.ToLower().EndsWith(type.ToLower()))
                    {
                        return false;
                    }
                }
                return File.Exists(fileName);
            }
            catch (Exception ef)
            {
                return false;
            }
        }

        /// <summary>
        /// 獲取Excel的OLEDB字串
        /// </summary>
        /// <param name="fileName">Excel 文件名</param>
        /// <returns>OLEDB字串</returns>
        private static string getConnStr(string fileName)
        {
            string conn = "";
            try
            {
                conn = ReadConfig.getConnectionString("ExcelODBC");
            }
            catch (Exception ef)
            {
                conn="";
            }
            if ((conn == null)
                || (conn.Trim().Equals("")))
            {
                //源的定義
                conn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";"
                    + "Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
            }
            else
            {
                int t = conn.ToLower().IndexOf("data source");
                if (t > 0)
                {
                    int n = conn.ToLower().IndexOf(";", t);
                    if (n > 0)
                    {
                        string connb = conn.Substring(0, t - 1) + conn.Substring(n + 1, conn.Length - n - 1);
                        conn = connb;
                    }                    
                }
                conn = conn + "Data Source=" + fileName + ";";
            }
            return conn;
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章