0
我遇到問題以檢索Excel工作表中的列名稱。使用reader.GetName和OLEDB讀取列名稱問題Excel提供程序
我有一個Excel工作表,只有3中的第一行中的細胞與這3個值:
- 在A1
:甲
在B1:乙
- 在C1
: ABC
當我嘗試執行我的方法時,標籤顯示:
- A,B,A·B·C
而不是:
- A,B,ABC
我的代碼:
protected void btnExecute_Click(object sender, EventArgs e)
{
string fullFileName = @"C:\TEST.xls";
List<string> columns = new List<string>();
string connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;", fullFileName);
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
// Retrieves the first sheet
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string firstSheet = dt.Rows[0]["TABLE_NAME"].ToString();
// Retrieves the list column name
string query = string.Format("SELECT TOP 1 * FROM [{0}]", firstSheet);
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataReader reader = cmd.ExecuteReader();
for (int i = 0; i < reader.FieldCount; i++)
{
columns.Add(reader.GetName(i));
}
}
lblCols.Text = string.Join(",", columns.ToArray());
}
你有解決這個問題的想法嗎?
在此先感謝。
丹尼爾