【问题标题】:Read row number from Excel sheet using OLEDB Object使用 OLEDB 对象从 Excel 工作表中读取行号
【发布时间】:2015-09-12 05:52:19
【问题描述】:

我正在使用OLEDB 对象读取 Excel 文件并在数据表中返回数据。下面的 Excel 工作表有两列,已导入,但我也想用我的数据读取 Excel 行号。

这是我用来读取 Excel 文件的代码:

private DataTable ImportExcel2007(String strFilePath)
{
    if (!File.Exists(strFilePath)) return false;
    String strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;"
    + "Data Source=" + strFilePath + ";"
    + "Extended Properties='Excel 8.0;HDR=Yes'";
    OleDbConnection connExcel = new OleDbConnection(strExcelConn);
    OleDbCommand cmdExcel = new OleDbCommand();
    try
    {
        cmdExcel.Connection = connExcel;

        //Check if the Sheet Exists
        connExcel.Open();
        DataTable dtExcelSchema;
        //Get the Schema of the WorkBook
        dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        connExcel.Close();

        //Read Data from Sheet1
        connExcel.Open();
        OleDbDataAdapter da = new OleDbDataAdapter();
        DataSet ds = new DataSet();
        string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
        cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";

        //Range Query
        //cmdExcel.CommandText = "SELECT * From [" + SheetName + "A3:B5]";

        da.SelectCommand = cmdExcel;
        da.Fill(ds);
        connExcel.Close();
        return ds.Table[0];
    }
    catch
    {
        return null;
    }
    finally
    {
        cmdExcel.Dispose();
        connExcel.Dispose();
    }
}

我可以通过增加数据表中的新列来管理它,但是我可以应用带有 SELECT 语句的 WHERE 子句来返回来自不同行号的数据(应用增加的行号可能会失败)?

【问题讨论】:

    标签: c# asp.net .net excel oledb


    【解决方案1】:

    不幸的是,OLEDB 不允许您根据行号进行选择。你可以使用这样的东西:

    int rowNum = 0;
    foreach (DataTable dt in ds.Tables)
    {
        dt.Columns.Add("RowNum",typeof(Int32));
        rowNum = 1;
        foreach (DataRow dr in dt.Rows)
        {
            dr["RowNum"] = rowNum++;
        }
    }
    

    【讨论】:

    • 谢谢,但这对我没有帮助,因为 where 条件可能会从不同行号的工作表中选择记录。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多