当前位置: 首页 > news >正文

Excel 导入数据到GridControl中的方法

Excel 导入数据到GridControl中的方法

private void simpleButton1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Excel文件";
            ofd.FileName = "";
            ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            ofd.Filter = "所有文件(*.*)|*.*|Excel2003文件(*.xls)|*.xls|Excel2007文件(*.xlsx)|*.xlsx";
            ofd.ValidateNames = true;
            ofd.CheckFileExists = true;
            ofd.CheckPathExists = true;
            string strName = string.Empty;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                strName = ofd.FileName;
            }
            if (strName == "")
            {
                XtraMessageBox.Show("没有选择Excel文件!无法进行数据导入");
                return;
            }
            else
            {
                try
                {
                    DataSet myDs = new DataSet();
                    string text = string.Format("Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '{0}';Extended Properties=Excel 8.0", strName);
                    string excelFirstTableName = GetExcelFirstTableName(text);
                    myDs.Tables.Clear();
                    myDs.Clear();
                    this.gridControl1.DataSource = null;
                    OleDbConnection selectConnection = new OleDbConnection(text);
                    OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter(string.Format("select * from [{0}]", excelFirstTableName), selectConnection);
                    oleDbDataAdapter.Fill(myDs);
                    this.gridControl1.DataSource = myDs.Tables[0];
                    this.gridView1.PopulateColumns();
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show("从电子表格文件中装载数据异常!", ex.Message);
                }
            }
        }
 
        /// <summary>
        /// 返回Excel第一个工作表表名
        /// </summary>
        /// <param name="connectstring">excel连接字符串</param>
        /// <returns></returns>
        public static string GetExcelFirstTableName(string connectstring)
        {
            using (OleDbConnection connection = new OleDbConnection(connectstring))
            {
                string tableName = string.Empty;
                if (connection.State == ConnectionState.Closed)
                    connection.Open();
                DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if (dt != null && dt.Rows.Count > 0)
                {
                    tableName = ConvertTo<string>(dt.Rows[0][2]);
                }
                return tableName;
            }
        }
 
 
        /// <summary>
        /// 将数据转换为指定类型
        /// </summary>
        /// <typeparam name="T">转换的目标类型</typeparam>
        /// <param name="data">转换的数据</param>
        public static T ConvertTo<T>(object data)
        {
            if (data == null || Convert.IsDBNull(data))
                return default(T);
 
            object obj = ConvertTo(data, typeof(T));
            if (obj == null)
            {
                return default(T);
            }
            return (T)obj;
        }
 
        /// <summary>
        /// 将数据转换为指定类型
        /// </summary>
        /// <param name="data">转换的数据</param>
        /// <param name="targetType">转换的目标类型</param>
        public static object ConvertTo(object data, Type targetType)
        {
            if (data == null || Convert.IsDBNull(data))
            {
                return null;
            }
            Type type2 = data.GetType();
            if (targetType == type2)
            {
                return data;
            }
            if (((targetType == typeof(Guid)) || (targetType == typeof(Guid?))) && (type2 == typeof(string)))
            {
                if (string.IsNullOrEmpty(data.ToString()))
                {
                    return null;
                }
                return new Guid(data.ToString());
            }
            if (targetType.IsEnum)
            {
                try
                {
                    return Enum.Parse(targetType, data.ToString(), true);
                }
                catch
                {
                    return Enum.ToObject(targetType, data);
                }
            }
            if (targetType.IsGenericType)
            {
                targetType = targetType.GetGenericArguments()[0];
            }
            return Convert.ChangeType(data, targetType);
        }
 
 

相关文章:

  • C++ - 头文件基础(常用标准库头文件、自定义头文件、头文件引入方式、防止头文件重复包含机制)
  • 多模态大语言模型arxiv论文略读(六)
  • 计算机视觉——为什么 mAP 是目标检测的黄金标准
  • c# 企业级ADB通信示例
  • 使用 new EventSource 实现前端实时通信
  • 数智化重构供应商管理
  • Java大视界:解码航天遥测数据的银河密码——从GB到PB的技术革命
  • Dubbo 注册中心与服务发现
  • 健身管理小程序|基于java微信开发健身管理小程序的系统设计与实现(源码+数据库+文档)
  • Web框架 --- Web服务器和Web应用服务器
  • Baumer工业相机堡盟工业相机如何处理偶发十万分之一或百万分之一几率出现的黑图现象(C#)
  • R语言之mlr依赖包缺失警告之分析
  • 【Redis】——最佳实践
  • 【区块链安全 | 第三十六篇】合约审计之自毁函数
  • 找不到导入的项目“xxx\QtMsBuild\Qt.props”。请确认 Import 声明“$(QtMsBuild)\Qt.props”中计算结果为
  • R语言进行判别分析
  • 十二、buildroot系统 adb登录权限设置
  • GitHub 趋势日报 (2025年04月07日)
  • Axure 列表滚动:表头非常多(横向滚动方向)、分页(纵向滚动) | 基于动态面板的滚动方向和取消调整大小以适合内容两个属性进行实现
  • MySQL表操作
  • 大气建站工作室网站源码/青岛seo优化
  • 网站logo设计标准/电商网站平台搭建
  • 龙岩b2b平台推广公司/保定seo推广公司
  • 高端品牌网站建设服务/seo培训学院
  • 做资料分享网站/美国搜索引擎排名
  • 做分子生物实验常用网站/网页制作成品模板网站