0

ExcelシートからリピーターまたはGridViewにデータをバインドするための効率的で最も簡単な方法は何ですか。

4

4 に答える 4

2

OleDbDataAdapter作成するのは簡単だと思いますDataSet

に簡単にバインドできDataSetますgridview

例えば

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

任意の1つのライブラリまたはその他のライブラリを使用してExcelからデータを読み取り、必要に応じて(OLEDB Connection, COM Object結果を.Netオブジェクト(DataSet, DataTable)に配置した後。次に、にバインドDataSetしますRepeater

于 2012-09-20T13:52:55.610 に答える
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

まず、閲覧する必要があります

 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; //ここでファイル名を1つのテキストボックスに保持

次に、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();
        }
      }
    }

//GridviewへのExcelのアップロード

    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)
      {

      }
    }
   }
  }

Excel2007およびその他のバージョン.NetのGridviewにアップロードします。

手順:1)AccessDatabaseEngine.exe->(インストール)そして、いくつかのコードが上記のコードから変更されています。

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 に答える