将Excel文件中的数据导出

 public class OfficeTools
    {
        /// <summary>
        /// 导出Excel文件数据
        /// </summary>
        /// <param name="filePath">Excel文件路径</param>
        /// <returns>导出的Excel文件数据DataSet类型</returns>
        public static DataSet GetDataFromExcel(string filePath)
        {
            DataSet ds = new DataSet();
            string strConn;
            strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1'";
            OleDbConnection conn = new OleDbConnection(strConn);
            try
            {
                conn.Open();
                List<string> sheetsList = GetSheetsCount(conn);
                foreach (var sheet in sheetsList)
                {
                    String sql = "SELECT * FROM  [" + sheet + "]";
                    OleDbCommand cmd = new OleDbCommand(sql, conn);
                    OleDbDataAdapter odda = new OleDbDataAdapter(cmd);
                    odda.Fill(ds);
                }             
                return ds;
            }
            catch (Exception ex)
            {
                DataControl.WriteExceptionLog(ex);
                return null;
            }
            finally
            {
                conn.Close();
                ds.Dispose();
            }
        }

        /// <summary>
        /// 获取Excel文件中的工作表表名列表
        /// </summary>
        /// <param name="conn">OleDbConnection连接对象</param>
        /// <returns>工作表表名列表</returns>
        private static List<string> GetSheetsCount(OleDbConnection conn)
        {
            List<string> sheetList = new List<string>();
            DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
            int rows = dt.Rows.Count;
            for (int i = 0; i < rows; i++)
            {
                if (!dt.Rows[i]["TABLE_NAME"].ToString().Contains("_"))
                {
                    sheetList.Add(dt.Rows[i]["TABLE_NAME"].ToString());
                }
            }
            return sheetList;
        }
    }

你可能感兴趣的:(exception,String,properties,Excel,null,dataset)