简体   繁体   中英

Move to the right row reading an Excel file in c#

I need to read an .xlsx file without use 3rd-part library.

I do in this way:

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();
}

I don't know how to read in the right cell. The problem isn't the column position (I can use , but the row position.

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

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

    s = excelReader(column_value);

    return s;
}

I created, and use, the following class to read the first sheet from the .xlsx or .xls file:

/// <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; }
    }
}

It returns the sheet as a DataTable .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM