【问题标题】:Why I cannot open a CSV file using JQuery and FileContentResult为什么我无法使用 JQuery 和 FileContentResult 打开 CSV 文件
【发布时间】:2021-04-22 11:57:45
【问题描述】:

我正在尝试进行 ajax 调用(我特别不想使用 ActionLink)。

我有一个这样的控制器:

public IActionResult ExportUsers(List<string> listOfEmails)
{
     /*some data processing*/
     return File(result, "text/csv", "ExportCandidates.csv");
}

在 ajax 的另一边,我做了这个简单的调用:

        $.ajax({
            url: '/Admin/Testcenter/GenerateInvitationPreview',
            type: 'post',
            data: {
                    //some input data to send to the controller   ​
           ​},
           ​success: function (response) {
               ​)
           ​}
       ​});

我知道 pdf 文件存在某些内容,您可以在其中返回 base64 文件,并在 ajax 调用中进行响应,您只需编写类似 pdfWindow.document.write(...) 的内容,这将打开一个带有 pdf 的新窗口文件。

有没有办法提取我的 CSV 文件的响应并生成它以便用户下载它?

【问题讨论】:

    标签: javascript c# ajax asp.net-mvc


    【解决方案1】:
    USE NPOI Library for Excel Sheet Generation  
    
      //Generate Excel Sheet
            try
                    {
                        Guid gid = Guid.NewGuid();
                        string ext = ".xls";
                        string[] Headers = { "Appointments Id", "Date of Appointment", "Doctor Name", "Patient Name", "Visit Type", "Status" };
                        string fileName = "AppointmentsExcelSheet_" + gid.ToString() + ext;
                        var serverpath = _env.ContentRootPath;
                        string rootpath = serverpath + "/wwwroot/ExcelSheets/" + fileName;
                        FileInfo file = new FileInfo(Path.Combine(rootpath, fileName));
                        var memorystream = new MemoryStream();
                        using (var fs = new FileStream(rootpath, FileMode.Create, FileAccess.Write))
                        {
        
                            IWorkbook workbook = new XSSFWorkbook();
                            ISheet excelSheet = workbook.CreateSheet("Appointments List");
                            IRow row = excelSheet.CreateRow(0);
                            var font = workbook.CreateFont();
                            font.FontHeightInPoints = 11;
                            font.FontName = "Calibri";
                            font.Boldweight = (short)FontBoldWeight.Bold;
                            for (var i = 0; i < Headers.Length; i++)
                            {
                                var cell = row.CreateCell(i);
                                cell.SetCellValue(Headers[i]);
                                cell.CellStyle = workbook.CreateCellStyle();
                                cell.CellStyle.SetFont(font);
                            }
        
                            var result = _Appointment.GetAppoinmentsPDf();
                            int index = 1;
                            foreach (var app in result.Items)
                            {
                                //var PatientDob = Convert.ToDouble(app.PatientDOB);
                                row = excelSheet.CreateRow(index);
                                row.CreateCell(0).SetCellValue(app.AppointmentId);
                                row.CreateCell(1).SetCellValue(app.DateofAppointment+" "+app.TimeofAppointment);
                                row.CreateCell(2).SetCellValue(app.DoctorFullName);
                                row.CreateCell(3).SetCellValue(app.SelectedPatientName);
                                row.CreateCell(4).SetCellValue(app.PurposeofVisit);
                                if (app.IsActive == false)
                                {
                                    row.CreateCell(5).SetCellValue("Inactive");
                                }
                                else
                                {
                                    row.CreateCell(5).SetCellValue("Active");
                                }
                                index++;
                            }
                            workbook.Write(fs);
                        }
                        using (var filestream = new FileStream(rootpath, FileMode.Open))
                        {
                            filestream.CopyToAsync(memorystream);
                        }
                        memorystream.Position = 0;
                        //send filepath to JQuery function
                        response.Msg = "/ExcelSheets/" + fileName;
        
                    }
                    catch (Exception Ex)
                    {
                      //exception code
                    }
               return Ok(reponse.Msg)
        //JavaScript
        function AppointmentsExcelSheet() {
            //var token = Token;
            //var link = path;
            debugger
            $.ajax({
                //'Content-Type': 'application/pdf.',
                type: "GET",
                url: "/api/Appointments/GetAppointmentsExcelSheet",
                beforeSend: function () {
                    $.blockUI({
                        message: ('<img src="/images/FadingLines.gif"/>'),
                        css: {
                            backgroundColor: 'none',
                            border: '0',
                            'z-index': 'auto'
                        }
                    });
                },
                complete: function () {
                    $.unblockUI();
                },
               
                success: function (data) {
                    debugger
                    //downloads your Excel sheet
                    window.location.href = data.msg;
                    
                }
        
            });
        
        }
    

    【讨论】:

      【解决方案2】:

      做你想做的最好的方法是不使用 AJAX,而是使用打开一个新窗口的链接单击(因为你正在传递参数)如果你可以使用一个

      <form target="_blank">
      

      打开表单响应。表单内部可以是包含电子邮件列表的一个或多个字段(可以是一个字段,也可以是多个具有相同名称的输入字段)。您的操作处理程序可以接受该列表,对其进行解析并返回一个 File 响应,从表单发布操作打开新窗口的自然结果是打开一个文件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-14
        • 1970-01-01
        • 2022-08-16
        • 1970-01-01
        • 1970-01-01
        • 2021-07-13
        • 1970-01-01
        相关资源
        最近更新 更多