• C# Excel文件导入操作


    Excel文件导出的操作我们经经常使用到,可是讲一个Excel文档导入并显示到界面还是第一次用到。

    以下简介下在C#下怎样进行Excel文件的导入操作。

    首先加入两个引用

    using System.IO;
    using System.Data.OleDb;

    加入控件openFileDialog

    然后我们须要配置Excel的OleDb连接字符串

    <span style="font-size:14px;">public const string OledbConnString = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = {0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; //Excel的 OleDb 连接字符串</span>

    选择一个Excel文件
            /// <summary>
            /// 选择EXCEL
            /// </summary>
            private void btn_BrowserExcel_Click(object sender, EventArgs e)
            {
                DialogResult dr = this.openFileDialog1.ShowDialog();
                if (DialogResult.OK == dr) //推断是否选择文件
                {
                    this.txtPath.Text = this.openFileDialog1.FileName;
                    this.btn_Import.Enabled = true;
                }
            }

    运行导入的操作且绑定数据源
            /// <summary>
            /// 运行导入操作
            /// </summary>
            private void btn_Import_Click(object sender, EventArgs e)
            {
                string path = this.txtPath.Text.Trim();
                if (string.IsNullOrEmpty(path))
                {
                    MessageBox.Show("请选择要导入的EXCEL文件。", "信息");
                    return;
                }
                if (!File.Exists(path))  //推断文件是否存在
                {
                    MessageBox.Show("信息", "找不到相应的Excel文件,请又一次选择。");
                    this.btn_BrowserExcel.Focus();
                    return;
                }
                DataTable excelTbl = this.GetExcelTable(path);  //调用函数获取Excel中的信息
                if (excelTbl == null)
                {
                    return;
                }
    
                DgvImport.DataSource = excelTbl;
    
            }

    最核心的功能在这里:

            /// <summary>
            /// 获取Excel文件里的信息,保存到一个DataTable中
            /// </summary>
            /// <param name="path">文件路径</param>
            /// <returns>返回生成的DataTable</returns>
            private DataTable GetExcelTable(string path)
            {
                try
                {
                    //获取excel数据
                    DataTable dt1 = new DataTable("excelTable");
                    string strConn = string.Format(OledbConnString, path);
                    OleDbConnection conn = new OleDbConnection(strConn);
                    conn.Open();
                    DataTable dt = conn.GetSchema("Tables");
                    //推断excel的sheet页数量,查询第1页
                    if (dt.Rows.Count > 0)
                    {
                        string selSqlStr = string.Format("select * from [{0}]", dt.Rows[0]["TABLE_NAME"]);
                        OleDbDataAdapter oleDa = new OleDbDataAdapter(selSqlStr, conn);
                        oleDa.Fill(dt1);
                    }
                    conn.Close();
                    return dt1;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Excel转换DataTable出错:" + ex.Message);
                    return null;
                }
            }
          效果图:

                                            

           看到这里大家肯定会有种似曾相识的感觉,最上面配置连接字符串,这里的GetExcelTable方法。打开连接,查询语句,运行命令,填充table。关闭连接。不就是从数据库查询数据过程的翻版吗?

           果然知识都是相通的。

           事实上这篇博客能够结合之前的一篇文章《批量保存数据 List 的使用 》,利用List<>泛型集合将 表格中数据保存到数据库。

    
  • 相关阅读:
    【上线复盘】20190329-一个刷新数据的接口是如何导致几十万的订单数据错误
    VS------csc.exe已停止工作解决方法
    SQLServer------存储过程的使用
    SQLServer------聚集索引和非聚集索引的区别
    SQLServer------Sql Server性能优化辅助指标SET STATISTICS TIME ON和SET STATISTICS IO ON
    SQLServer------如何快速插入几万条测试数据
    SQLServer------如何让标识列重新开始计算
    SQLServer------begin tran/commit tran事务的使用方法
    SQLServer------插入数据时出现IDENTITY_INSERT错误
    Spring----Spring Boot Rest的使用方法
  • 原文地址:https://www.cnblogs.com/claireyuancy/p/6951595.html
Copyright © 2020-2023  润新知