C# .NET - How to all user to import excel data correctly

Asked By Erik Little on 16-Sep-13 11:20 AM
I've found quite a few ways on the internet to import data from a sheet that is in an excel file uploaded by the user into an sql table.

Here are a few of my questions / comments.

1.) I need to be able to make sure each column name is spelled correctly in the excel file.

2.) I need to make sure that if excel string data is longer than column schema for the table that sql will allow for that excel sheet data to continue to be inserted, but will be truncated.

3.) I've got three different sql tables so there will need to be three different excel sheets, my questions is would it be OK to have one excel file that contains three different sheets that correspond to the three different tables, or should I ask the user to upload one sheet at time?

So, the recap I need a comprehensive explanation / documentation to read so I can allow my users to upload excel files to my servers and then process those files and insert that excel sheet data into specific sql data tables.

To make it sound even easier I need to loop each sheet in an excel file and if the sheet name is the table name, THEN I'll loop the columns in that sheet to verify that the column names are correct, if so the do a bulk insert.

Any help is greatly appreciated!

Erik

Robbe Morris replied to Erik Little on 16-Sep-13 11:44 AM
You'll want to purchase a product called spreadsheetgear.com.  There are others but I think these guys are the best.  It permits you to work with the Excel file safely in a web environment, desktop app, or windows service.  Microsoft Excel doesn't work at all or work safely/well in these environments.

You'll find the object model to be pretty darn close between spreadsheetgear and Microsoft Excel's VBA capabilities.

You'll be able to easily iterate through sheets, columns on sheets, various ranges, all the stuff you'd need to do.

If you are not familiar with the object model and need help getting started with the code, what I always suggest to people is to use the Macro Recorder feature in Excel.  Essentially, you start the recorder, manually perform by hand want you want to write in code, after you are finished, stop the recorder.  Then, look at the VBA code generated.  With spreadsheetgear, it will give  you a huge head start on writing code because the object model is largely the same.  You'll just have to account for the differences in VBA to C#.  Not hard at all.  They also have a ton of samples in C# to read from.