【问题标题】:Import excel header data in a drop down in .net在 .net 的下拉列表中导入 excel 标题数据
【发布时间】:2014-01-09 15:43:26
【问题描述】:

您好,我正在使用 Visual Studio 2005 中的 OpenFileDialog 导入 excel 或 .csv 文件。 我需要在列表中显示所有标题,该列表应该列在 ComboBox 上。

例如,如果我导入一个包含 10 列的文件,我的下拉菜单应显示 10 个值 1, 2, 3........10

请告诉我该怎么做。

【问题讨论】:

    标签: c# excel visual-studio import


    【解决方案1】:

    CSV 与 Excel 完全不同。

    我会使用 OpenXml 库或使用 OleDb 驱动程序来读取 excel 文件。

    看这里:Reading excel file using OLEDB Data Provider

    您需要安装 ACE 驱动程序,但您可能已经安装了它。

    【讨论】:

      【解决方案2】:
      // first read *.xls file into a DataTable; don't wory it is very quick.
      public DataTable ReadExcelFile(string strFilePath)
      {
          string sConnectionString  = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + strFilePath + "; Extended Properties=\"Excel 8.0; HDR=No; IMEX=1;\"";
          OleDbConnection objConn = new OleDbConnection(sConnectionString);
          objConn.Open();
          DataTable sdt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
          // Change this part to read 1 row    
          String str = "SELECT TOP(2) * FROM [" + sdt.Rows[0]["TABLE_NAME"].ToString() + "]";
          //String str = "SELECT * FROM [" + sdt.Rows[0]["TABLE_NAME"].ToString() + "]";
          OleDbCommand objCmdSelect = new OleDbCommand(str, objConn);
          OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
          objAdapter1.SelectCommand = objCmdSelect;
          DataTable dt = new DataTable();
      
          objAdapter1.Fill(dt);
      
          objConn.Close();
          dt.AcceptChanges();
      
          return dt;
      }
      

      现在使用 DataTable

      DataTable dt = ReadExcelFile(@"c:\\x.xlsx");
      if (dt != null)
      {
          System.Windows.Forms.ComboBox cmb = new System.Windows.Forms.ComboBox();
          for (int i = 0; i < dt.Columns.Count; i++)
              cmb.Items.Insert(i, dt.Columns[i].ColumnName);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多