我想使用实体框架使用ASP.NET MVC将Excel文件数据导入和导出到SQL Server 。
我发现的所有代码都说明了这一点,而没有使用实体框架。那我该怎么做呢?
EPPlus是一个.NET库,它使用Open Office Xml格式(xlsx)读写Excel 2007/2010文件。这是在ASP.net MVC中使用此库的示例代码。
public FileContentResult Download()
{
var fileDownloadName = String.Format("FileName.xlsx");
const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
// Pass your ef data to method
ExcelPackage package = GenerateExcelFile(_db.Contexts.ToList());
var fsr = new FileContentResult(package.GetAsByteArray(), contentType);
fsr.FileDownloadName = fileDownloadName;
return fsr;
}
private static ExcelPackage GenerateExcelFile(IEnumerable<Context> datasource)
{
ExcelPackage pck = new ExcelPackage();
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet 1");
// Sets Headers
ws.Cells[1, 1].Value = "Column 1";
ws.Cells[1, 2].Value = "Column 2";
ws.Cells[1, 3].Value = "Column 3";
// Inserts Data
for (int i = 0; i < datasource.Count(); i++)
{
ws.Cells[i + 2, 1].Value = datasource.ElementAt(i).Serial;
ws.Cells[i + 2, 2].Value = datasource.ElementAt(i).WarrantyStart;
ws.Cells[i + 2, 3].Value = datasource.ElementAt(i).WarrantyEnd;
}
// Format Header of Table
using (ExcelRange rng = ws.Cells["A1:C1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.Gold); //Set color to DarkGray
rng.Style.Font.Color.SetColor(Color.Black);
}
return pck;
}
并在您的视图中插入此链接,它将下载您的文件。
@Html.ActionLink("Download Data as Excel", "Download");
同样,您可以从excel导入数据,这是一个入门示例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句