简体   繁体   中英

Read Excel file

I am writing some code to read an excel file, but unfortuantely the excel file contains more than 300 columns and I need to read all 300.

I've been using some 3rd Part libraries to do this LinqToExcel but they can only read a maximum of 256 columns

        var excel = new ExcelQueryFactory(FileName);

        var recs = (from ws in excel.Worksheet<Sample>("data export final")
                    select ws).ToList()

Does anyone know how I can read all 300 columns, preferabbly without having to install Microst Office as this will be running on a server which doesn't have that installed

EPPlus can read and write > 256 columns. Here's a short example showing writing to column 300.

FileInfo newFile = new FileInfo(@"C:\Temp\sample300.xlsx");
if (newFile.Exists)
{
    newFile.Delete();  // ensures we create a new workbook
    newFile = new FileInfo(@"C:\Temp\sample300.xlsx");
}

using (ExcelPackage package = new ExcelPackage(newFile))
{
    // add a new worksheet to the empty workbook
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Inventory");
    //Add the headers
    worksheet.Cells[1, 1].Value = "ID";
    worksheet.Cells[1, 300].Value = "Col 300";
    package.Save();
}

Reading from column 300+ is just as easy, but it's harder to post a self-contained example that includes a large input file :-)

There are several options - all involve some additional library:

OpenXML 2.0 (free library from MS) can be used to read/modify the content of an .xlsx so you can do with it what you want

some (commercial) 3rd-party libraries come with grid controls allowing you to do much more with excel files in your application (be it Winforms/WPF/ASP.NET...) like SpreadsheetGear, Aspose.Cells etc.

You can try with this code based on OleDbDataAdapter

            string filename = @"....xls";
            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                                          "Data Source=" + filename + ";" +
                                          "Extended Properties=Excel 8.0;";

            OleDbDataAdapter dataAdapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
            DataSet myDataSet = new DataSet();
            dataAdapter.Fill(myDataSet, "Sample");
            DataTable dataTable = myDataSet.Tables["Sample"];


            var rows = from p in dataTable.AsEnumerable()
                       select new 
                       {
                           Property = p.Field<string>("Column")
                       };

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