简体   繁体   English

从数据库中提取数据并使用 ASP.NET Core MVC 将其保存为 Excel 文件

[英]Extract data from the database and save it as an Excel file using ASP.NET Core MVC

I have written a web application to get the data from the database in which the user would select the start date and end date of the data they want to have and then submit which later is saved to an Excel file.我编写了一个 web 应用程序来从数据库中获取数据,用户将在其中 select 他们想要拥有的数据的开始日期和结束日期,然后提交,然后将其保存到 ZC1D81AF5835844B4E9D936910 文件中。

The application only works when not attached to the form, however it doesn't do anything when I include the start date and end date.该应用程序仅在未附加到表单时才有效,但是当我包含开始日期和结束日期时它不会做任何事情。

Here is my HomeController code snippet:这是我的HomeController代码片段:

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; }
        }        
    }

    
}

My view model form is as follows;我的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; }
            
        
        }
        
        
        
    }
}

and finally my view is as follow, which is what I want to get the data for the specified dates by the user in the database;最后我的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>

This is how the form displays in the browser and once the user click submit, then an Excel file should be generated with an option to save it from the data from the db with the user's specified dates.这就是表单在浏览器中的显示方式,一旦用户单击提交,则应生成一个 Excel 文件,并带有一个选项,可以从数据库中的数据中保存它,并使用用户指定的日期。 在此处输入图像描述

I have figured it out so what I did was change a line in my view file,我已经想通了,所以我所做的是在我的视图文件中更改一行,

<form method="post" asp-controller="Home" asp-action="Index" >

changed to:变成:

<form method="post" asp-controller="Home" asp-action="ExportExcelData" >

and have added a class in my Controller并在我的 Controller 中添加了Controller

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

Which I then changed my ExportExcelData class to;然后我将我的ExportExcelData class 更改为;

        [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");


             }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 上传Excel文件并提取数据 - asp.net mvc 3 - Upload Excel file and extract data - asp.net mvc 3 如何在 ASP.NET MVC 中使用 HttpGet 将数据保存到数据库中? - How to save data into database using HttpGet in ASP.NET MVC? 使用ASP.NET MVC Core将数据从数据库注入到类中 - Inject data from database to a class with ASP.NET MVC Core Excel文件使用asp.net C#读取数据并将其保存在SQL Server数据库中 - Excel file read and save data in SQL Server database using asp.net c# 将数据从本地 excel 文件加载到 ASP.NET MVC web 应用程序以存储在数据库中 - Load data from local excel file to an ASP.NET MVC web app to store in database 使用asp.net将用户数据保存到Excel文件 - Using asp.net to save users data to Excel file 来自Google文档的Excel使用asp.net C#读取数据并将其保存在SQL Server数据库中 - Excel from Google Docs read and save data in SQL Server database using asp.net c# 如何使用 C# 在 ASP.NET Core MVC 中创建网格,在其中插入记录并将整个数据保存到数据库中? - How to create a grid in ASP.NET Core MVC using C# in which we insert the record and save the whole data to the database? 当我尝试将数据从 db 提取到 ASP.NET MVC 和 C# 中的 excel 文件中时,出现匿名类型错误 - I get an anonymous type error when I try to extract data from db into excel file in ASP.NET MVC & C# 如何使用ASP.net MVC从数据库中获取数据? - How to fetch data from database using ASP.net MVC?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM