简体   繁体   中英

Read excel file in c#

I have a excel file. I want to get data of this.

I use this code.

public static DataTable ConvertToDataTable(ExcelDocument source, bool hasTitle = true)
{
    if (source == null)
        return null;
    // Get range of used data in excel file.
    Excel.Range excelCell = source.WorkSheet.UsedRange;

    // Get data of range and save it to array.
    Object[,] valuesExcel = (Object[,])excelCell.Value2;
    if (valuesExcel == null)
        return null;
    DataTable dataTable = new DataTable();
    DataRow dataRow;

    // We may have two rows,first for datatable's name and second for datatable's header.
    // We check first(datatable's name) is exist.
    int startRow = (hasTitle) ? 2 : 1;

    int rowIndex;
    int columnIndex;
    int rowsCount;
    int columnsCount;

    // Get count of rows.
    rowsCount = valuesExcel.GetLength(0);

    if (rowsCount != 0)
    {
        // Get count of columns.
        columnsCount = valuesExcel.GetLength(1);
        if (columnsCount != 0)
        {
            for (columnIndex = 1; columnIndex <= columnsCount; columnIndex++)
            {
                // Create column headrs.
                dataTable.Columns.Add(new DataColumn((String)valuesExcel[startRow, columnIndex]));
            }
            columnsCount = dataTable.Columns.Count;
            for (rowIndex = 3; rowIndex <= rowsCount; rowIndex++)
            {
                // Create new row ,fill it and set cells.
                dataRow = dataTable.NewRow();
                for (columnIndex = 1; columnIndex <= columnsCount; columnIndex++)
                {
                    // set data for any cells.
                    dataRow[(String)valuesExcel[startRow, columnIndex]] = valuesExcel[rowIndex, columnIndex];
                }
                dataTable.Rows.Add(dataRow);
            }
        }
    }
    return dataTable;

}

But rowsCount = valuesExcel.GetLength(0); and columnsCount = valuesExcel.GetLength(1); get empty column and row.

For example , i have a file that records in 13 rows and 6 columns. but when i use this code i get a rowcount=34 and columncount=20.

My file have rows and colmns empty.

Your Excel file is not sanitized. Because you are using UsedRange , you are getting cells that at one point had data in them.

You have 2 options:

  1. Fix the Excel file by opening it up and actually deleting the columns and rows. Just deleting the cell contents won't do it -- it just makes it blank. Select your rows and columns and actually delete them.

  2. Add logic to your code to try and detect if a row or column should be ignored.

Well,

I have always had the need to get data from excel to my dbs, and by far most satisfying solution is Excel Data Reader from CodePlex. Snippet of my code:

FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read);
Excel.ExcelBinaryReader reader = Excel.ExcelReaderFactory.CreateBinaryReader(fs) as Excel.ExcelBinaryReader;
reader.IsFirstRowAsColumnNames = true;

DataSet ds = reader.AsDataSet();
foreach (DataRow dr in ds.Tables[0].Rows)
{
    ;
}

It can also read xmls excel fileformats via

CreateOpenXmlReader() method.

It works flawlessly.

You should check it out.

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