【问题标题】:Move to the right row reading an Excel file in c#在 C# 中移动到读取 Excel 文件的右侧行
【发布时间】:2015-10-26 11:18:48
【问题描述】:

我需要在不使用第三部分库的情况下读取 .xlsx 文件。

我是这样做的:

private void Upload(string filename)
{
    FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read);

    // Reading from a OpenXml Excel file (2007 format; *.xlsx)
    IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

    //DataSet - The result of each spreadsheet will be created in the result.Tables
    excelReader.IsFirstRowAsColumnNames = false;
    DataSet result = excelReader.AsDataSet();

    //5. Data Reader methods
   string value = GetValue(0, 0, excelReader);

    //6. Free resources (IExcelDataReader is IDisposable)
    excelReader.Close();
}

我不知道如何在正确的单元格中阅读。问题不在于列位置(我可以使用 ,而是行位置。

public string GetValue(int row, int col, IExcelDataReader excelReader)
{
    string s;

    // ??? how to positionate on the right row?

    s = excelReader(column_value);

    return s;
}

【问题讨论】:

标签: c# excel parsing


【解决方案1】:

我创建并使用以下类从.xlsx.xls 文件中读取第一张表:

/// <summary>
/// Reads a table from a spreadsheet.
/// </summary>
public sealed class XlsxReader
{
    /// <summary>
    /// Loads an xlsx file from a filepath into the datatable.
    /// </summary>
    /// <param name="filePath"></param>
    /// <returns>Returns a DataTable with data from the first sheet.</returns>
    public static DataTable FromXLSX(string filePath)
    {
        try
        {
            // Create the new datatable.
            DataTable dtexcel = new DataTable();

            // Define the SQL for querying the Excel spreadsheet.
            bool hasHeaders = true;
            string HDR = hasHeaders ? "Yes" : "No";
            string strConn;

            // If it is a xlsx file
            if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=1;\"";
            else
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=1;\"";

            // Create connection
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();

            // Get scheme
            DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
            DataRow schemaRow = schemaTable.Rows[0];

            // Get sheet name
            string sheet = schemaRow["TABLE_NAME"].ToString();
            if (!sheet.EndsWith("_"))
            {
                // Query data from the sheet
                string query = "SELECT  * FROM [" + sheet + "]";
                OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
                dtexcel.Locale = CultureInfo.CurrentCulture;

                // Fill the datatable.
                daexcel.Fill(dtexcel);
            }

            // Close connection.
            conn.Close();

            // Set the datatable.
            return dtexcel;
        }
        catch { throw; }
    }
}

它将工作表返回为DataTable

【讨论】:

  • 但是这样我无法指定我想要的单元格。
  • 不,你必须得到正确的行。可以使用列名,例如dt.Rows[2]["MyColumn"].ToString(),也可以只使用列号,例如:dt.Rows[2][2].ToString()
  • 不适用于列名...如果我使用dt.Rows[i]["A"].ToString(); 不起作用...如果我使用像dt.Rows[i][j].ToString(); 这样的索引则可以。
  • A 不是列名。如果我有一个表Name | Description,那么描述在语法中使用是有效的。如果我想要第一行的描述,dt.Rows[0]["Description"].ToString()。它使用第一行中的数据在DataTable 中创建列名。
  • 只需创建一个以letter 作为输入并输出number 的函数。或者让它接受像B2 这样的单元格名称并让它输出“坐标”。您甚至可以创建一个函数,将列名称 (string) B2DataTable 作为 input,并让它 output 只是那个单元格值作为 string
猜你喜欢
  • 2013-10-26
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-26
  • 1970-01-01
  • 2018-04-19
相关资源
最近更新 更多