zoukankan      html  css  js  c++  java
  • WinForm窗体下Excel的导入

    一、Winform窗体程序的Excel的导入

    把Excel导入到内存中的DataTable

    方法实现:

    #region ExcelToDataTable
    public static DataTable ExcelToDataTable(string strExcelFileName,string strSheetName)
    {
        try
        {
            //源的定义
            string strConn = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + strExcelFileName + ";Extended Properties="Excel 8.0;HDR=Yes;IMEX=1;"";
                    //Sql语句
                    string strExcel = string.Format("select   *   from   [{0}$] ", strSheetName);
                    //string strExcel = "select   *   from     [sheet1$] ";
    
                    //定义存放的数据表
                    DataSet ds = new DataSet();
    
                    //连接数据源
                    OleDbConnection conn = new OleDbConnection(strConn);
    
                    conn.Open();
    
                    //适配到数据源
                    OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
                    adapter.Fill(ds, strSheetName);
    
                    conn.Close();
    
                    return ds.Tables[strSheetName];
                }
                catch
                {
                    return null;
                }
        }
    }
    #rendregion
    View Code

    导入事件实现:

    首先是Excel导入检验和获取数据

      #region 导入Excel
            private void ExportExcelExport_EventExport(object sender, EventArgs e)
            {
                #region Excel导入检验和获取数据
                if (this.textFilePath.Text == "")
                {
                    MessageBox.Show("请选择要导入的文件!");
                    return;
                }
                if (!File.Exists(textFilePath.Text))
                {
                    MessageBox.Show("该路径下文件不存在!");
                    return;
                }
                MessageProcess.InfoShow("开始读取文件数据.........");
                DataSet dsTmp = CommonMethod.ExcelToDataTable(this.textFilePath.Text);
                DataTable exceldt = dsTmp.Tables[0];
                if (OperateUI.HaveData(exceldt))
                {
                    MessageProcess.InfoShow("成功获取数据,开始进行数据处理");
                }
                else
                {
                    MessageProcess.InfoShow("获取不到数据,可能文件有误");
                    return;
                } 
                #endregion
    }
            #endregion
    View Code

    导入Excel成功后,可以进行excel中的数据,与数据库的数据进行比较,或者修改数据的数据等一系列操作。

    by author:Foreordination

    2018-02-01 10:40:52

  • 相关阅读:
    google搜索技巧
    sqlite,mysql,access对比
    【转】python技术博客
    2013待阅读书目
    【转】larbin的代码实现逻辑概述
    【转】python遍历文件夹和文件
    【转】正则表达式高级讲解
    Atitit.mybatis的测试  以及spring与mybatis在本项目中的集成配置说明
    Atitit.100% 多个子元素自适应布局属性
    atitti.atiNav 手机导航组件的设计
  • 原文地址:https://www.cnblogs.com/drq1/p/8397815.html
Copyright © 2011-2022 走看看