【问题标题】:Extract data from the database and save it as an Excel file using ASP.NET Core MVC使用 ASP.NET Core MVC 从数据库中提取数据并保存为 Excel 文件
【发布时间】:2021-03-08 19:08:29
【问题描述】:

我编写了一个 Web 应用程序来从数据库中获取数据,用户可以在其中选择他们想要拥有的数据的开始日期和结束日期,然后提交,然后将其保存到 Excel 文件中。

该应用程序仅在未附加到表单时才有效,但是当我包含开始日期和结束日期时它不会执行任何操作。

这是我的HomeController代码sn-p:

namespace Task1.Controllers
{
    public class HomeController : Controller
    {
        // GET
        [HttpGet]
        public IActionResult Index()
        {
            var model = new FormBoard();
            
            var form = new FormBoard.Form();
            form.StartDate = DateTime.UtcNow;
            form.EndDate = DateTime.UtcNow;
            
            return View(model);
        }
 
        [HttpPost]
        public IActionResult ExportExcelData(FormBoard viewModel)
        {
            IEnumerable<ReportData> results;
            var connection = @"server=remoteserver;Database=introsw;Uid=root;Pwd=12345";

            using var con = new SqlConnection(connection);
            {
                 con.Open();
                 results = con.Query<ReportData>(@"SELECT 
                         document_date as [DocumentDate],
                         document_number as [DocumentNumber], 
                         description as [Description],
                         project__code as [ProjectCode],
                         project__name as [ProjectName],
                         client__name as [ClientName],
                         client__account as [ClientAccount],
                         total_incl_vat as [TotalIncVat]
                             FROM
                         customer_documents_full_view
                             WHERE 
                         document_date BETWEEN 'StartDate' AND 'EndDate'
                          ");
                 
             XLWorkbook workbook = new XLWorkbook();
             workbook.Worksheets.Add("Sample").Cell(1, 1).SetValue(results);
             var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                 
             MemoryStream memoryStream = new MemoryStream();
             workbook.SaveAs((Stream) memoryStream);
             memoryStream.Seek(0L, SeekOrigin.Begin);
                 
             var content = memoryStream.ToArray();
             Console.Write(content);
                 
             return File(content, contentType, "Datafile.xlsx");
        } 
        
        public class ReportData
        {
            public DateTime DocumentDate { get; set; }
            public string DocumentNumber { get; set; }
            public string Description { get; set; }
            public string ProjectCode { get; set; }
            public string ProjectName { get; set; }
            public string ClientName { get; set; }
            public string ClientAccount { get; set; }
            public Decimal TotalIncVat { get; set; }
        }        
    }

    
}

我的view model表格如下;

using System;
using System.ComponentModel.DataAnnotations;

namespace Task1.ViewModels
{
    public class FormBoard
    {
       
        public class Form
        {
            public int Id { get; set; }
            
            //  start date 
            [Required]
            public DateTime StartDate { get; set; }
            // end data
            [Required]
            public DateTime EndDate { get; set; }
            
        
        }
        
        
        
    }
}

最后我的view如下,这是我想在数据库中获取用户指定日期的数据;

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@model Task1.ViewModels.FormBoard

@{
    ViewData["Title"] = "Index";
}

<!DOCTYPE html>
<html>
<head>
        <!-- Compiled and minified CSS -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
        
        <!-- Compiled and minified JavaScript -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
                
</head>

<body>
    <div class="container">
        <div class="row">
            <h2>Fill in Date</h2>
            <form method="post" asp-controller="Home" asp-action="Index" >
                <div>
                    <label >Start:</label>
                    <input type="date" name="StartDate" 
                           class="input-validation-error"
                           data-val="true"
                           data-val-required="The start date field is required"
                           id="StartDate" value="">
                </div>
                
                <div>
                    <label >End:</label>
                    <input type="date" name="EndDate" >
                </div>

                <div class="center">
                    <button type="submit" class="btn" >Submit</button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>

这就是表单在浏览器中的显示方式,一旦用户单击提交,就会生成一个 Excel 文件,其中包含一个选项,可以从数据库中的数据中保存它,并使用用户指定的日期。

【问题讨论】:

    标签: c# asp.net-core-mvc


    【解决方案1】:

    我已经想通了,所以我所做的就是在我的视图文件中更改一行,

    &lt;form method="post" asp-controller="Home" asp-action="Index" &gt;

    改为:

    &lt;form method="post" asp-controller="Home" asp-action="ExportExcelData" &gt;

    并在我的Controller 中添加了一个类

    public class ReportParams
            {
                public DateTime StartDate { get; set; }
                public DateTime EndDate { get; set; }
                
            }
    
    

    然后我将 ExportExcelData 课程更改为;

            [HttpPost]
            public IActionResult ExportExcelData(ReportParams reportParams)
                 {
                     IEnumerable<ReportData> results;
                     var connection = @"server=remoteserver;Database=introsw;Uid=root;Pwd=12345";
                     using var con = new SqlConnection(connection);
                    
                     con.Open();
                     results = con.Query<ReportData>(@"SELECT 
                             document_date as [DocumentDate],
                             document_number as [DocumentNumber], 
                             description as [Description],
                             project__code as [ProjectCode],
                             project__name as [ProjectName],
                             client__name as [ClientName],
                             client__account as [ClientAccount],
                             total_incl_vat as [TotalIncVat]
                                 FROM
                             customer_documents_full_view
                                 WHERE 
                             document_date BETWEEN @StartDate AND @EndDate
                              ", reportParams);
                     
                     XLWorkbook workbook = new XLWorkbook();
                     workbook.Worksheets.Add("Sample").Cell(1, 1).SetValue(results);
                     var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                     
                     MemoryStream memoryStream = new MemoryStream();
                     workbook.SaveAs((Stream) memoryStream);
                     memoryStream.Seek(0L, SeekOrigin.Begin);
                     
                     var content = memoryStream.ToArray();
                     Console.Write(content);
                     Console.WriteLine("Export Excel Data");
    
                 
                     return File(content, contentType, "Datafile.xlsx");
    
    
                 }
    

    【讨论】:

      猜你喜欢
      • 2012-06-29
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      相关资源
      最近更新 更多