![](/img/trans.png)
[英]Problem with using OleDbDataAdapter to fetch data from a Excel sheet
[英]Excel to Grid view issues using OleDbDataAdapter
我正在使用Visual Studio 2010創建Windows窗體應用程序。
我使用OleDbDataAdapter方法從excel文件中將數據填充到DataGridView。
這是我的代碼
dataGridView1.DataSource = null;
dataGridView1.Update();
var connectionString =
string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=No;IMEX=1\";", fileName);
var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
var ds = new DataSet();
DataTable t = new DataTable();
adapter.Fill(t);
dataGridView1.DataSource = t;
現在問題是如果某些單元格在excel文件輸出中合並得有點不同。 這是更好理解的圖像。
那么我該如何解決這個問題呢?
我想如果我可以識別合並單元格,那么我可以解決這個問題。 但目前我還沒有明確的想法。
有沒有更好的方法在網格視圖中表示excel數據,就像在excel文件中一樣?
任何答案都會有所幫助。 請分享任何建議。
謝謝
勒芒
我的解決方案
protected void Page_Load(object sender, EventArgs e)
{
string path = @"C:\samples\firstexcel.xlsx";
GetExcelSheetNames(path);
}
private void GetExcelSheetNames(string excelFile)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet ds = new DataSet();
// Connection String.
String connString = @"Data Source=" + excelFile + ";
Provider=Microsoft.ACE.OLEDB.12.0; Extended Properties=Excel 12.0;";
// Create connection.
objConn = new OleDbConnection(connString);
// Opens connection with the database.
objConn.Open();
// Get the data table containing the schema guid, and also sheet names.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
// And respective data will be put into dataset table
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_name"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(ds, "TABLE");
i++;
}
// Bind the data to the GridView
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
Session["Table"] = ds.Tables[0];
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
// Clean up.
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = ((DataTable)Session["Table"]).DefaultView;
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{;}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.