I understand that this question was asked almost 7 years ago, but it is still the best Google search result for certain keywords regarding importing Excel data from C #, so I wanted to provide an alternative based on some recent technical developments.
Importing Excel data has become so common in my day-to-day responsibilities that I simplified the process and documented the method on my blog: the best way to read an Excel file in c # .
I use NPOI because it can read / write Excel files without Microsoft Office installed and does not use COM + or any operations. This means that it can work in the cloud!
But the real magic is pairing with Donny Tian's NPOI Mapper, because it allows me to map Excel columns to properties in my C # classes without writing any code. It is beautiful.
Here is the basic idea:
I create a .net class that matches / maps the Excel columns that interest me:
class CustomExcelFormat { [Column("District")] public int District { get; set; } [Column("DM")] public string FullName { get; set; } [Column("Email Address")] public string EmailAddress { get; set; } [Column("Username")] public string Username { get; set; } public string FirstName { get { return Username.Split('.')[0]; } } public string LastName { get { return Username.Split('.')[1]; } } }
Please note this allows me to display based on the column name if I want!
Then, when I process the Excel file, all I need to do is something like this:
public void Execute(string localPath, int sheetIndex) { IWorkbook workbook; using (FileStream file = new FileStream(localPath, FileMode.Open, FileAccess.Read)) { workbook = WorkbookFactory.Create(file); } var importer = new Mapper(workbook); var items = importer.Take<CustomExcelFormat>(sheetIndex); foreach(var item in items) { var row = item.Value; if (string.IsNullOrEmpty(row.EmailAddress)) continue; UpdateUser(row); } DataContext.SaveChanges(); }
Now, admittedly, my code does not modify the excel file itself. Instead, I save the data in the database using the Entity Framework (which is why you see "UpdateUser" and "SaveChanges" in my example). But SO already has a good discussion on how to save / modify the file using NPOI .
Dan Feb 18 '19 at 13:18 2019-02-18 13:18
source share