I’m sure at some point you’ve needed to read some Excel files in an application. You’ve probably even used the Office Interop libraries (using something like: new Excel.Application();). Below I’ll show a much easier way that makes use of a data model to read an Excel file using LinqToExcel. If you’re looking for the complete code, scroll to the end of the page.
- Start a new solutions / project. In my example I’m just using a console app.
- Make sure you save your solution before running step 3, or you’ll get a “The current environment doesn’t have a solution open.” error.
- In the Package Manager Console, at the “PM>” prompt, enter “Install-Package LinqToExcel” and press enter. When complete, it should read: “Successfully added ‘LinqToExcel 1.10.1’ to…”
- Add these lines to the very top of your code (if not already there):
using System;
using System.Linq;
using LinqToExcel;
using LinqToExcel.Attributes; - Add your data model. I’m using an Excel spreadsheet that contains the planets sizes and masses (taken from this sweet NASA page). Why? Because it’s really cool.
My model looks like:internal class Planet { [ExcelColumn("Planetary Body")] public string Name { get; set; } [ExcelColumn("Mass (1024kg)")] public double Mass { get; set; } [ExcelColumn("Diameter (km)")] public int Diameter { get; set; } }
- Notice how the ExcelColumn attribute contains the formatted name of the column (with spaces, etc.). Make sure these match to your Excel columns.
- Now in your Main method, let’s add some code to read the Excel file (replacing the below w/ your file path, model name and sheet name (“Planets” in the below):
var excel = new ExcelQueryFactory(@"F:\cbitting\Planets.xlsx") { DatabaseEngine = LinqToExcel.Domain.DatabaseEngine.Ace, TrimSpaces = LinqToExcel.Query.TrimSpacesType.Both, UsePersistentConnection = true, ReadOnly = true }; var planets = from p in excel.Worksheet<Planet>("Planets") select p;
- Now let’s add something to see what data this retrieved:
foreach (Planet planet in planets) { Console.WriteLine(planet.Name + " Mass: " + planet.Mass); } Console.ReadLine();
- Your results should be the data in your Excel file.
You can filter the data in the Linq statement using something like:
var planets = from p in excel.Worksheet<Planet>("Planets") where p.Diameter > 5000 select p;
Or order the data using:
foreach (Planet planet in planets.OrderByDescending(p => p.Diameter))
This is a very simple example of this powerful method of reading Excel spreadsheets. https://github.com/paulyoder/LinqToExcel has many more examples and documentation.
If you’re looking to use this on a machine without Office installed, I believe you need https://www.microsoft.com/en-au/download/details.aspx?id=13255 to enable ACE.
Below is the entire code from this example:
using System; using System.Linq; using LinqToExcel; using LinqToExcel.Attributes; namespace cSharpExcelRead { internal class Planet { [ExcelColumn("Planetary Body")] public string Name { get; set; } [ExcelColumn("Mass (1024kg)")] public double Mass { get; set; } [ExcelColumn("Diameter (km)")] public int Diameter { get; set; } } internal class Program { private static void Main(string[] args) { var excel = new ExcelQueryFactory(@"F:\cbitting\Planets.xlsx") { DatabaseEngine = LinqToExcel.Domain.DatabaseEngine.Ace, TrimSpaces = LinqToExcel.Query.TrimSpacesType.Both, UsePersistentConnection = true, ReadOnly = true }; var planets = from p in excel.Worksheet<Planet>("Planets") select p; foreach (Planet planet in planets.OrderByDescending(p => p.Diameter)) { Console.WriteLine(planet.Name + " Mass: " + planet.Mass); } Console.ReadLine(); } } }
hi i am trying to import excel data using LinqToExcel in my asp.net mvc project but i am importing the one excel.excel have the 2 column 1 is Itemcode and 2 is Quantity.Quantity column store the one row data is 0.8 then upload excel value is replace “0.8” to “0”. not getting propare value.this is below code i am used.
LikeLike
Hey, send me a sample of your file and I’ll try to give you hand. Should be easy.
LikeLike
Can we read excel cell comments using this library??
LikeLike
I don’t believe so.
LikeLike
Nice, but Has dependency of provider Microsoft.ACE.OLEDB.12.0
working after install:
2010 (installed an work)
https://www.microsoft.com/en-us/download/confirmation.aspx?id=13255
LikeLiked by 1 person
What If the excel column has two lines? How can I define it in my Model ExcelColumn
LikeLike
Good question. You mean 1 cell but with a line break?
LikeLike
Yes, It has a line break. How can I define that in my object properties? Because I’m experiencing it in my project that I’m getting null value because it cannot find the column header that I’m calling because it has two lines.
LikeLike
What If the excel column header has two lines? How can I define it in my Model ExcelColumn
LikeLike