0

将数据从 excel 工作表绑定到中继器或 GridView 的有效且最简单的方法是什么?

4

4 回答 4

2

OleDbDataAdapter我认为创建和创建遗嘱很容易DataSet完成这项工作。

您可以轻松地将 a 绑定DataSetgridview

例如

var conn = ("Provider=Microsoft.Jet.OLEDB.4.0;" + 
            ("Data Source=add file path here;" +                                
            "Extended Properties=\"Excel 8.0;\"")); 

var query = "SELECT table from [sheet1$]";

var adpterObj = new OleDbDataAdapter(SSQL, conn); 

var ds = new DataSet();

adpterObj.Fill(ds);
GridView1.DataSource = ds.Tables[0].DefaultView; 
GridView1.DataBind();
于 2012-09-20T13:54:12.833 回答
1

首先我们要浏览

 void btnBrowse_Click(object sender, EventArgs e)
 {
   OpenFileDialog fileDialog = new OpenFileDialog();
   fileDialog.Filter = "Excel files (*.xls)|*.xls";
   fileDialog.InitialDirectory = "C:";
   fileDialog.Title = "Select a Excel file";
   if (fileDialog.ShowDialog() == DialogResult.OK)
    txtMsg.Text = fileDialog.FileName;
   if (string.IsNullOrEmpty(txtMsg.Text))
   return;
 }

注意:txtMsg.Text = fileDialog.FileName; //这里文件名保存在一个文本框中

然后我们可以上传excel表格到gridview...

 private void btnUpload_Click(object sender, EventArgs e)
 {
    if (!string.IsNullOrEmpty(txtMsg.Text))
    {
       InsertBuyBackExceldata(txtMsg.Text);
    }
 }

这里我们可以调用 InsertBuyBackExceldata 方法

  void InsertBuyBackExceldata(string filePath)
  {
       if (buyBackServiceProxyController == null)
         buyBackServiceProxyController = new ProxyController();
       buyBackServiceServiceProxy = buyBackServiceProxyController.GetProxy();


       ListBuyBackrequest = new List();
       String[] a= GetExcelSheetNames(filePath); // This method for get sheet names
       var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", filePath);
       //string a=filePath.
        String sheetName = a[0];
       var adapter = new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", connectionString);
       var ds = new DataSet();

       adapter.Fill(ds, sheetName );

       DataTable data = ds.Tables[sheetName ];

       BindGrid(data);
  }

在这里,我正在调用一种方法来获取工作表名称。

   private String[] GetExcelSheetNames(string excelFile)
   {
         OleDbConnection objConn = null;
         System.Data.DataTable dt = null;

      try
      {
         String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
           "Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";

         objConn = new OleDbConnection(connString);

         objConn.Open();

         dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

         if (dt == null)
         {
              return null;
         }

       String[] excelSheets = new String[dt.Rows.Count];
       int i = 0;

      foreach (DataRow row in dt.Rows)
      {
            excelSheets[i] = row["TABLE_NAME"].ToString();
             i++;
      }

      return excelSheets;
    }
     catch (Exception ex)
     {
         return null;
     }
     finally
     {
          if (objConn != null)
          {
            objConn.Close();
            objConn.Dispose();
       }
        if (dt != null)
        {
            dt.Dispose();
        }
      }
    }

//Excel上传到Gridview

    void BindGrid(DataTable Data)
    {
     try
     {
      // Adding one check box
      DataGridViewCheckBoxColumn chkSelection = new DataGridViewCheckBoxColumn();
      chkSelection.Name = "Selection";
      dgItemsForBuyBackGrid.Columns.Add(chkSelection);
      int intCount = Data.Rows.Count;
      if (i==true)
      {
       if (intCount > 0)
       {
         ExcelGrid.DataSource = Data;
         ExcelGrid.BindPage();
       }
        else
       {
          ExcelGrid.DataSource = null;
          ExcelGrid.BindPage();
          return;
       }
      // Here I am setting Grid colomns properties this name should equal to Excel //column names.
       ExcelGrid.Columns["BI"].ReadOnly = true;
       ExcelGrid.Columns["AAA"].ReadOnly = true;
       ExcelGrid.Columns["AAB"].ReadOnly = true;
       ExcelGrid.Columns["AAC"].ReadOnly = true;
       ExcelGrid.Columns["AAD"].ReadOnly = true;
       ExcelGrid.Columns["AAE"].ReadOnly = true;
       ExcelGrid.Columns["AAF"].ReadOnly = true;
       ExcelGrid.Columns["AAG"].ReadOnly = false;
      }
      else
      {
         // Some Code
        }
     }
      catch (Exception ex)
      {

      }
    }
   }
  }

Excel 2007 和其他版本上传到 .Net 中的 Gridview。

步骤: 1) AccessDatabaseEngine.exe --> (Install) 和上面代码的一些代码变化。

2) 浏览点击

   private void btnBrowse_Click(object sender, EventArgs e)
   {
      -------
      fileDialog.Filter ="Excel files (*.xls;*xlsx;*xlsb)|*.xls;*xlsx;*xlsb";
      // Show those extentional files.
       --------------
    }

3) 处理点击

    string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;";

谢谢你 :)

于 2012-10-18T07:06:16.113 回答
1

也许这个链接会解决你的问题

点我

public static DataSet ImportExcelXLS(string FileName, bool hasHeaders) {
string HDR = hasHeaders ? "Yes" : "No";
string strConn;
if (FileName.Substring(FileName.LastIndexOf('.')).ToLower() == ".xlsx")
    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
else
    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";

DataSet output = new DataSet();

using (OleDbConnection conn = new OleDbConnection(strConn)) {
    conn.Open();

    DataTable schemaTable = conn.GetOleDbSchemaTable(
        OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

    foreach (DataRow schemaRow in schemaTable.Rows) {
        string sheet = schemaRow["TABLE_NAME"].ToString();

        if (!sheet.EndsWith("_")) {
            try {
                OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
                cmd.CommandType = CommandType.Text;

                DataTable outputTable = new DataTable(sheet);
                output.Tables.Add(outputTable);
                new OleDbDataAdapter(cmd).Fill(outputTable);
            } catch (Exception ex) {
                throw new Exception(ex.Message + string.Format("Sheet:{0}.File:F{1}", sheet, FileName), ex);
            }
        }
    }
}
return output;
} 
于 2012-09-20T13:58:21.070 回答
1

您应该使用任何一个库或任何其他库从 Excel 中读取数据,然后根据您的要求(OLEDB Connection, COM Object将结果放入任何 .Net 对象 ( )。DataSet, DataTable然后绑定DataSet到你的Repeater.

于 2012-09-20T13:52:55.610 回答