使用 reader.GetName 和 OLEDB Excel 提供程序读取列名称问题
我在检索 Excel 工作表中的列名称时遇到问题。
我有一个 Excel 工作表,第一行只有 3 个单元格,其中包含以下 3 个值:
in A1: A
in B1: B
in 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());
}
你有想法吗解决这个问题??
提前致谢。
丹尼尔
I have an issue to retrieve the columns names in an Excel sheet.
I have an Excel sheet with only 3 cells in the first row with these 3 values:
in A1: A
in B1: B
in C1: A.B.C
When I try to execute my method the label shows:
- A,B,A#B#C
And not:
- A,B,A.B.C
My Code:
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());
}
Do you have an idea to fix this issue??
Thanks in advance.
Daniel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个我通过堆栈溢出发布的OleDBAdapter Excel QA。
我刚刚对此进行了测试,它从您描述的示例 .xls 中获取了“ABC”。
即在底部添加以下内容以进行快速测试:
Try this OleDBAdapter Excel QA I posted via stack overflow.
I just tested this and it picked up "A.B.C" from a sample .xls you described.
i.e. add the following to the bottom for a quick test: