2

我从这里获得了以下代码来使用 C# .NET 读取 Excel 文件:

string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbCommand command = connection.CreateCommand()
command.CommandText = "SELECT City,State FROM [Cities$]";

我想从第 4 行开始只选择 10 行,我该怎么做?

4

1 回答 1

2

我不是 Excel 查询专家,但这确实有效。使用 TOP 将查询限制为 13 行。第一行是带有列名的标题,因此它可能不算数。如果我误解了,显然会改变。然后,跟踪行 ID 并对 4 上或之后的行进行处理。

希望这可以帮助!

string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connectionString)) {
    System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
    cmd.Connection = conn;
    cmd.CommandText = "SELECT top 13 City,State FROM [Cities$]";

    conn.Open();
    System.Data.IDataReader dr = cmd.ExecuteReader();

    int row = 2;
    while (dr.Read()) {
        if (row++ >= 4) {
            // do stuff
            Console.WriteLine("{0}, {1}", dr[0], dr[1]);
        }
    }
}
于 2008-11-13T03:11:23.780 回答