Scalar

态度决定一切,正能量走起!

导航

C# 操作Excel文件

1、判断操作系统是否有安装Excel

//引用
    using Microsoft.Win32;

    public class Helper
    {
        //C# 操作Excel文件

        //引用
        using Microsoft.Win32;

        /// <summary>
        /// 判断操作系统是否安装Excel
        /// </summary>
        /// <returns></returns>
        public static bool CheckExcel()
        {
            bool flag = false;  
        
            RegistryKey root = Registry.ClassesRoot;

            if (null != root)
            {
                RegistryKey excelSheet = root.OpenSubKey("Excel.Sheet");
                if (null != excelSheet)
                {
                    RegistryKey curVer = excelSheet.OpenSubKey("CurVer");
                    if (null != curVer)
                    {
                        flag = true;
                    }
                }
            }

            return flag;
        }
    }

2、使用OLEDB读取Excel文件。eg:

//引用   
using System.Data.OleDb;

        /// <summary>
        /// 读取Excel文件
        /// </summary>
        /// <param name="strExcelFileName">Excel文件路径</param>
        /// <param name="strSheetName">工作簿名称</param>
        /// <returns>返回表格</returns>
        private DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)
        {
            DataTable table = null;
            string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strExcelFileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';";
            string strExcel = string.Format("select * from [{0}$]", strSheetName);
            DataSet ds = new DataSet();
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();

            OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
            adapter.Fill(ds, strSheetName);
            conn.Close();
            table = ds.Tables[strSheetName];

            return table;
        }

 

 

 

 

    

posted on 2012-06-06 20:09  Scalar  阅读(165)  评论(0)    收藏  举报