C# 读取Excel文件

public System.Data.DataTable GetExcelToDataTable(string filePath)
        {
         
            System.Data.DataTable daExcelInfo = new System.Data.DataTable();

            string strSheet = string.Empty;

            Microsoft.Office.Interop.Excel.Application obj = default(Microsoft.Office.Interop.Excel.Application);
            Microsoft.Office.Interop.Excel.Workbook objWB = default(Microsoft.Office.Interop.Excel.Workbook);

            obj = (Microsoft.Office.Interop.Excel.Application)Microsoft.VisualBasic.Interaction.CreateObject("Excel.Application", string.Empty);
            objWB = obj.Workbooks.Open(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                                 Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                                 Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                                 Type.Missing, Type.Missing);

            if (objWB.Worksheets.Count > 0)
            {
                strSheet = ((Microsoft.Office.Interop.Excel.Worksheet)objWB.Worksheets[1]).Name;
            }
            else
            {
                strSheet = "Sheet1";
            }
            objWB.Close(Type.Missing, Type.Missing, Type.Missing);
            objWB = null;
            obj.Quit();
            obj = null;

                DataSet dsExcelData = new DataSet();

                string strConnection = "provider=Microsoft.Jet.OLEDB.4.0; Extended Properties='Excel 8.0;HDR=NO;IMEX=1'; data source=" + filePath + "; ";
                OleDbConnection odConnection = null;
                try
                {
                    odConnection = new OleDbConnection(strConnection);
                    OleDbDataAdapter odDataAdapter = new OleDbDataAdapter();
                    OleDbCommand odCommand = new OleDbCommand();
                    odCommand.Connection = odConnection;
                    odConnection.Open();
                    odCommand.CommandType = CommandType.Text;
                    odCommand.CommandText = "SELECT * FROM [" + strSheet + "$]";
                    odDataAdapter.SelectCommand = odCommand;
                    odDataAdapter.Fill(dsExcelData);

                }
                catch (OleDbException ex)
                {
                    daExcelInfo = null;
                }
                finally
                {
                    if (odConnection != null)
                        odConnection.Close();                 
                }
                if (dsExcelData.Tables.Count > 0)
                {
                    daExcelInfo = dsExcelData.Tables[0];
                }
                else
                {
                    daExcelInfo = null;
                }
           return daExcelInfo;
        }

你可能感兴趣的:(C# 读取Excel文件)