C# 并从 Excel 文件中读取值 [英] C# and read values from an Excel file

查看:37
本文介绍了C# 并从 Excel 文件中读取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Excel 文件,列有名称(数据源不受我控制.它是由客户提供给我的).尽管列发生了变化,但列标题永远不会改变.

I have an Excel file and the columns have names (data source is NOT controlled by me.. it's given to me by a client). Although the columns change, the column headers never change.

在文件中,它被称为名字"

In the file, it's called "First Name"

如何访问同一列中每个单元格中的数据?

How do I access the data in every cell within the same column?

推荐答案

将 Excel 文件作为数据库打开.那么你就不必担心列的位置了:

Open your Excel file as a database. Then you will not have to bother about the position of the columns:

string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\MyExcelFile.xls;Extended Properties=\"Excel 8.0;HDR=YES\"";
using (var conn = new System.Data.OleDb.OleDbConnection(connString)) {
    conn.Open();
    System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("Select * From [SheetName$]", conn);
    OleDbDataReader reader = cmd.ExecuteReader();
    int firstNameOrdinal = reader.GetOrdinal("First Name");
    int lastNameOrdinal = reader.GetOrdinal("Last Name");
    while (reader.Read()) {
        Console.WriteLine("First Name: {0}, Last Name: {1}", 
            reader.GetString(firstNameOrdinal), 
            reader.GetString(lastNameOrdinal));
    }
}

这篇关于C# 并从 Excel 文件中读取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆