.net core3.1 从数据库读取数据(导出)到excel表(导出)实战
我的数据表结构:
1.编写从数据库读取数据的相关业务逻辑(省略,若对我的业务逻辑代码感兴趣,可私聊)
2.编写导出到excel表的代码
控制器部分代码如下:
/// <summary> /// 导出数据 /// </summary> /// <returns></returns> [Route("ExportData")] public IActionResult ExportData() { //TODO 从数据库读取数据相关业务逻辑需要自己编写 var data = lawyerLogic.GetLawyers()?.ToList(); if (data?.Any() != true) { return new ContentResult() {Content = "未查询到任何数据"}; } ExcelPackage.LicenseContext = LicenseContext.NonCommercial; using (var ep = new ExcelPackage()) { using (var worksheet = ep.Workbook.Worksheets.Add("导出数据测试")) { var x = 1; var y = 1; var columnTitles = new List<string>() { "律师编号", "律师名称", "状态" }; foreach (var columnTitle in columnTitles) { var cell = worksheet.Cells[x, y++]; cell.Style.Font.Bold = true; cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center; cell.Value = columnTitle; } foreach (var item in data) { x++; y = 1; var cell = worksheet.Cells[x, y++]; cell.Value = item.LawyerId; cell = worksheet.Cells[x, y++]; cell.Value = item.LawyerName; cell = worksheet.Cells[x, y++]; cell.Value = (int)item.Status; } using (var stream = new MemoryStream()) { ep.SaveAs(stream); return new FileContentResult(stream.ToArray(),"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName="导出数据测试.xlsx" }; } } } }
以上便是我的.net core3.1 从数据库读取数据(导出)到excel表过程及代码,若有不足之处请指正,谢谢。