c# - Getting Excel data to SQL table with EPPlus and SqlBulkCopy -
i have added epplus library solution. can't seem figure out how excel data datatable allow bulkcopy work. below code doesn't work. can me massage place? thank in advance assistance. have edited after comments 'mason' below.
try { //// open file var excel = request.files[0]; var file = path.combine(server.mappath("~/uploads/"), excel.filename); var sqlconnectionstring = configurationmanager.connectionstrings["mydb"].tostring(); // datatable procedure on utility.cs page var datapush = utility.importtodatatable(file, "sheet1"); // open connection sql , use bulk copy write exceldata table using (var destinationconnection = new sqlconnection(sqlconnectionstring)) { destinationconnection.open(); using (var bulkcopy = new sqlbulkcopy(destinationconnection)) { bulkcopy.destinationtablename = "mytable"; bulkcopy.columnmappings.add("code", "code"); bulkcopy.columnmappings.add("title", "title"); bulkcopy.columnmappings.add("last_name", "last_name"); bulkcopy.columnmappings.add("first_name", "first_name"); bulkcopy.writetoserver(datapush); } } }
and here code on utility.cs page based on mason's suggested link:
public class utility { public static datatable importtodatatable(string filepath, string sheetname) { datatable dt = new datatable(); fileinfo fi = new fileinfo(filepath); // check if file exists if (!fi.exists) throw new exception("file " + filepath + " not exists"); using (excelpackage xlpackage = new excelpackage(fi)) { // first worksheet in workbook excelworksheet worksheet = xlpackage.workbook.worksheets[sheetname]; // fetch worksheet size excelcelladdress startcell = worksheet.dimension.start; excelcelladdress endcell = worksheet.dimension.end; // create needed datacolumn (int col = startcell.column; col <= endcell.column; col++) dt.columns.add(col.tostring()); // place data datatable (int row = startcell.row; row <= endcell.row; row++) { datarow dr = dt.newrow(); int x = 0; (int col = startcell.column; col <= endcell.column; col++) { dr[x++] = worksheet.cells[row, col].value; } dt.rows.add(dr); } } return dt; }
}
currently when run code , f11 bug on utility.cs page. right after "// first worksheet in workbook"
excelworksheet worksheet = xlpackage.workbook.worksheets[sheetname];
returns null , next line of code
excelcelladdress startcell = worksheet.dimension.start;
stops , kicks following error "{"object reference not set instance of object."}"
Comments
Post a Comment