Optimal way to Read an Excel file (.xls/.xlsx)

后端 未结 7 1780
一生所求
一生所求 2020-11-27 12:01

I know that there are different ways to read an Excel file:

  • Iterop
  • Oledb
  • Open Xml SDK

C

7条回答
  •  粉色の甜心
    2020-11-27 12:16

    Using OLE Query, it's quite simple (e.g. sheetName is Sheet1):

    DataTable LoadWorksheetInDataTable(string fileName, string sheetName)
    {           
        DataTable sheetData = new DataTable();
        using (OleDbConnection conn = this.returnConnection(fileName))
        {
           conn.Open();
           // retrieve the data using data adapter
           OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "$]", conn);
           sheetAdapter.Fill(sheetData);
           conn.Close();
        }                        
        return sheetData;
    }
    
    private OleDbConnection returnConnection(string fileName)
    {
        return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
    }
    

    For newer Excel versions:

    return new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;");
    

    You can also use Excel Data Reader an open source project on CodePlex. Its works really well to export data from Excel sheets.

    The sample code given on the link specified:

    FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
    
    //1. Reading from a binary Excel file ('97-2003 format; *.xls)
    IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
    //...
    //2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
    IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
    //...
    //3. DataSet - The result of each spreadsheet will be created in the result.Tables
    DataSet result = excelReader.AsDataSet();
    //...
    //4. DataSet - Create column names from first row
    excelReader.IsFirstRowAsColumnNames = true;
    DataSet result = excelReader.AsDataSet();
    
    //5. Data Reader methods
    while (excelReader.Read())
    {
    //excelReader.GetInt32(0);
    }
    
    //6. Free resources (IExcelDataReader is IDisposable)
    excelReader.Close();
    

    Reference: How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

提交回复
热议问题