本文介绍了如何使用mvc.net将数据从excel导入数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请帮助我尝试使用Entity Framework和MVC将我的导入数据从excel修复到数据库。
错误我得到的状态是以下代码是UNREACHABLE
for(int row = 2; ws.Cells [row,col] .Value!= null; row ++)
。
因此,由于这个错误,每当我运行我的代码时,我的FOR代码都会被跳过。
我尝试过:
public ActionResult Import()
{
if (Request.Files.Count> 0)
{
var file = Request.Files [0];
尝试
{
使用(var p = new ExcelPackage(file.InputStream))
{
ExcelWorksheet ws = p.Workbook.Worksheets [1];
int col = 1;
//将记录插入数据库表。
EntertainmentEntities entities = new EntertainmentEntities();
for(int row = 2; ws.Cells [row,col] .Value!= null; row ++)
{
entities.Music.Add(new Music
{
Artist = ws.Cells [row,1] .Value.ToString(),
Song = ws.Cells [row,2] .Value.ToString(),
Genre = ws.Cells [row,3] .Value.ToString(),
MusicDate =(int)ws.Cells [row,4] .Value
});
entities.SaveChanges();
返回查看(索引);
}
}
}
catch
{
ViewBag.Message =Error;
}
}
其他
{}
返回查看(导入);
}
解决方案
Please kindly assist me with trying to fix my import data from excel to a database using Entity Framework along with MVC.
The error i have been getting states that the following code is UNREACHABLE
for (int row = 2; ws.Cells[row, col].Value != null; row++ )
.
So because of this error, whenever I run my code, my FOR code is been skipped.
What I have tried:
public ActionResult Import() { if (Request.Files.Count > 0) { var file = Request.Files[0]; try { using (var p = new ExcelPackage(file.InputStream)) { ExcelWorksheet ws = p.Workbook.Worksheets[1]; int col = 1; //Insert records to database table. EntertainmentEntities entities = new EntertainmentEntities(); for (int row = 2; ws.Cells[row, col].Value != null; row++ ) { entities.Music.Add(new Music { Artist = ws.Cells[row, 1].Value.ToString(), Song = ws.Cells[row, 2].Value.ToString(), Genre = ws.Cells[row, 3].Value.ToString(), MusicDate = (int)ws.Cells[row, 4].Value }); entities.SaveChanges(); return View("Index"); } } } catch { ViewBag.Message = "Error"; } } else { } return View("Import"); }
解决方案
这篇关于如何使用mvc.net将数据从excel导入数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!