Kendo Grid Export CSV is not working

2 Answers 346 Views
Grid
Anil
Top achievements
Rank 1
Anil asked on 06 Jan 2022, 09:30 AM | edited on 06 Jan 2022, 09:32 AM

I have a kendo grid with custom control. Kendo Grid Export CSV is not working for me. Source code is given below. Can anyone help me.

Code running without error but CSV is not generating ( chrome).

1. kendo grid.
    .Name("PayrollReport")
    .ToolBar(toolbar =>
    {
        toolbar.Excel().HtmlAttributes(new { @class = "toolbar-field" });
        toolbar.Custom()
                        .Text("Export To CSV")
                        .HtmlAttributes(new { id = "exportCSV" });

jquerry

 

  $("#PayrollReport").on("click", "#exportCSV", function (e) {

            var batchid = $("#ddlbatchidamexrpt").data("kendoDropDownList").value();
            var status = $("#ddlpayrollstatus").data("kendoDropDownList").value();
            //debugger;
              $.ajax({
                type: "POST",
                url: "/Home/ExportServer",
                  data: JSON.stringify({ 'Batchid': batchid, 'Status': status }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    //alert("Saved Successfully");
                },
                failure: function (response) {
                    //alert("Error Occured");
                }
              });
            e.preventDefault();



        }); 

Home controller

 

  [HttpPost]
        public FileContentResult ExportServer(string Batchid,string Status)
        {
            var payrollrpt = svc.GetPayrollReport(Batchid, Status);
            StringBuilder sw = new StringBuilder();          

            sw.AppendLine("\"CompanyID\",\"BatchID\",\"Earning5Code\",\"Earning5Amount\"\"Earning5Code\",\"Earning5Amount\"\"Earning5Code\",\"Earning5Amount\"\"Earning5Code\",\"Earning5Amount\"\"Earning5Code\",\"Earning5Amount\"");
           
            sw.Append("\n");
            foreach (var line in payrollrpt)
            {
                sw.AppendLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\",\"{11}\"",
                                           line.CompanyID,
                                           line.BatchID,
                                           line.Earning5CodeTERTaxable,
                                           line.TaxableExpense,
                                           line.Earning5CodeHotel,
                                           line.HOTELTAX,
                                           line.Earning5CodeAir,
                                           line.AIRTAXB,
                                           line.Earning5CodeOther,
                                           line.TRNSRTAX,
                                           line.Earning5CodeMeals,
                                           line.Meals ));
              
                sw.Append("\n");
            }          
           
            return File(new System.Text.UTF8Encoding().GetBytes(sw.ToString()), "text/csv", "PayrollReport.csv");          

        }

 

            

2 Answers, 1 is accepted

Sort by
0
Neli
Telerik team
answered on 11 Jan 2022, 08:11 AM

Hello Anil,

I would suggest you take a look at the threads from StackOverflow and MSDN linked below were exporting to CSV is discussed:

https://stackoverflow.com/questions/26780912/stringbuilder-to-csv

https://stackoverflow.com/a/40780124

https://social.msdn.microsoft.com/Forums/vstudio/en-US/80fa29cf-a56f-45c4-8694-13db45627f99/how-to-create-a-csv-file-in-c-?forum=netfxbcl

I hope this helps. 

Regards,
Neli
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

0
Mani
Top achievements
Rank 1
Iron
answered on 21 Jul 2023, 11:17 AM

 .ToolBar(toolBar =>
                                            toolBar.Template("<a id='exportToExcelBtn' class='k-button k-button-icontext k-grid-excel btn btn-secondary btn-custom' style='float:right;margin-right:12px; display:none' href='#'><span class='k-icon k-i-excel' style='margin-top:-1px;'></span>Export To Excel</a> " +
                                            "<a id='exportToCsvBtn' class='k-button k-button-icontext btn btn-secondary btn-custom' style='float:right;margin-right:12px; display:none' href='javascript:getCSV()'><span class='k-icon' style='margin-top:-1px;'></span>Export To CSV</a>"                                             "</div>"))
                                    .Excel(excel => excel
                                    .FileName("Invoices.xlsx")
                                    .Filterable(true).AllPages(true)
                                    )

In toolbar you can add like this  for both the excel and csv will work 

function getCSV() {
         var grid = $("#gridInvoices").data("kendoGrid");
         var dataSource = grid.dataSource;
         var filter = dataSource.filter();
         parameterMap = grid.dataSource.transport.parameterMap;
         var requestObject = parameterMap({
             sort: grid.dataSource.sort(), filter: grid.dataSource.filter(), group: grid.dataSource.group(), page: grid.dataSource.page(),
             pageSize: grid.dataSource.pageSize()
         });

        $.ajax({
            url: "@Url.Action("YourMethodName", "YourControllerName")",
            type: 'post',
            data: requestObject,
            success: function (data) {

            // Optional: Handle success response, if needed
            var blob = new Blob([data]);

            // Create a temporary anchor element to trigger the download
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
                link.download = 'Invoices.csv';
            link.click();

            // Clean up the temporary anchor element
            link.remove();
                },

        error: function () {
            // Optional: Handle error response, if needed

        }
    });
    }

It will works  try like this

Tags
Grid
Asked by
Anil
Top achievements
Rank 1
Answers by
Neli
Telerik team
Mani
Top achievements
Rank 1
Iron
Share this question
or