使用EPPlus和SqlBulkCopy将Excel数据获取到SQL表

我已经添加了EPPlus库到我的解决scheme。 我似乎无法弄清楚如何让我的Excel数据成为一个数据表,这将允许我的批量复制工作。 下面的代码不起作用。 任何人都可以帮我按摩这个地方? 预先感谢您的帮助。 我在下面的“泥瓦匠”的评论后编辑了这个。

try { //// open file var excel = Request.Files[0]; var file = Path.Combine(Server.MapPath("~/Uploads/"), excel.FileName); var sqlConnectionString = ConfigurationManager.ConnectionStrings["MyDB"].ToString(); // Get the datatable from procedure on Utility.cs page var datapush = Utility.ImportToDataTable(file, "Sheet1"); // open connection to sql and use bulk copy to write excelData to my 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); } } } 

这里是基于梅森build议链接的Utility.cs页面上的代码:

 public class Utility { public static DataTable ImportToDataTable(string FilePath, string SheetName) { DataTable dt = new DataTable(); FileInfo fi = new FileInfo(FilePath); // Check if the file exists if (!fi.Exists) throw new Exception("File " + FilePath + " Does Not Exists"); using (ExcelPackage xlPackage = new ExcelPackage(fi)) { // get the first worksheet in the workbook ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[SheetName]; // Fetch the WorkSheet size ExcelCellAddress startCell = worksheet.Dimension.Start; ExcelCellAddress endCell = worksheet.Dimension.End; // create all the needed DataColumn for (int col = startCell.Column; col <= endCell.Column; col++) dt.Columns.Add(col.ToString()); // place all the data into DataTable for (int row = startCell.Row; row <= endCell.Row; row++) { DataRow dr = dt.NewRow(); int x = 0; for (int col = startCell.Column; col <= endCell.Column; col++) { dr[x++] = worksheet.Cells[row, col].Value; } dt.Rows.Add(dr); } } return dt; } 

}

目前,当我运行代码和F11的错误是在Utility.cs页面上。 在“//获取工作簿中的第一张工作表”之后

ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[SheetName];

返回null和下一行代码

ExcelCellAddress startCell = worksheet.Dimension.Start;

停止一切,并踢出以下错误“{”对象引用未设置为对象的实例。“}”