【问题标题】:JQGgrid- How to generate a pdf / excel file from the grid dataJQGgrid-如何从网格数据生成pdf/excel文件
【发布时间】:2026-02-09 10:00:01
【问题描述】:

我有以下 JQGrid 表,它是从 JSON 数据生成的。我希望能够根据可查看的表数据状态生成/导出或创建 pdf 文件。我正在使用 JSON、Jqgrid 和 Javascript

如何从数据中生成 pdf 文件? Here My FIDDLE

JS 代码

 $(document).ready(function() {
        var jsonData = {
          "Name": "Julie Brown",
          "Account": "C0010",
          "LoanApproved": "12/5/2015",
          "LastActivity": "4/1/2016",
          "PledgedPortfolio": "4012214.00875",
          "MaxApprovedLoanAmt": "2050877.824375",
          "LoanBalance": "1849000",
          "AvailableCredit": "201877.824375",
          "Aging": "3",
          "Brokerage": "My Broker",
          "Contact": "Robert L. Johnson",
          "ContactPhone": "(212) 902-3614",
          "RiskCategory": "Yellow",
          "rows": [{
            "ClientID": "C0010",
            "Symbol": "WEC",
            "Description": "Western Electric Co",
            "ShareQuantity": "20638",
            "SharePrice": "21.12",
            "TotalValue": "435874.56",
            "LTVCategory": "Equities",
            "LTVRatio": "50%",
            "MaxLoanAmt": "217937.28"
          }, {
            "ClientID": "C0010",
            "Symbol": "BBB",
            "Description": "Bins Breakers and Boxes",
            "ShareQuantity": "9623",
            "SharePrice": "74.29125",
            "TotalValue": "714904.69875",
            "LTVCategory": "Equities",
            "LTVRatio": "50%",
            "MaxLoanAmt": "357452.349375"
          }, {
            "ClientID": "C0010",
            "Symbol": "GPSC",
            "Description": "Great Plains Small Cap Stock",
            "ShareQuantity": "49612",
            "SharePrice": "14.24",
            "TotalValue": "706474.88",
            "LTVCategory": "Mutual Funds - Small Cap",
            "LTVRatio": "40%",
            "MaxLoanAmt": "282589.952"
          }]
        },
        mmddyyyy = "";
      /*********************************************************************/


      $("#output").jqGrid({
        url: "/echo/json/",
        mtype: "POST",
        datatype: "json",
        postData: {
              json: JSON.stringify(jsonData)
        },
        colModel: [
          /**    { name: 'ClientID', label:'ClientID',width: 80, key: true },****/
          {
            name: 'Symbol',
            width: 65
          }, {
            name: 'Description',
            width: 165
          }, {
            name: 'ShareQuantity',
            align: 'right',
            width: 85,
            classes: "hidden-xs", labelClasses: "hidden-xs",
            formatter: 'currency',
            formatoptions: {
              prefix: " ",
              suffix: " "
            }
          }, {
            name: 'SharePrice',
            label: 'Share Price',
            align: 'right',
            width: 100,
            classes: "hidden-xs", labelClasses: "hidden-xs",
            template: "number",
            formatoptions: {
              prefix: " $",
              decimalPlaces: 4
            }
          },
          /*{ label: 'Value1', 
                      name: 'Value1', 
                      width: 80, 
                      sorttype: 'number', 
                      formatter: 'number',
                      align: 'right'
                  }, */
          {
            name: 'TotalValue',
            label: 'Total Value',
            width: 160,
            sorttype: 'number',
            align: "right",
            search: false,
            formatter: 'currency',
            formatoptions: {
              prefix: " $",
              suffix: " "
            }
          }, {
            name: 'LTVRatio',
            label: 'LTV Ratio',
            width: 70,
            sorttype: 'number',
            align: "right",
            formatter: 'percentage',
            formatoptions: {
              prefix: " ",
              suffix: " "
            }
          }, {
            name: 'LTVCategory',
            label: 'LTV Category',
            classes: "hidden-xs", labelClasses: "hidden-xs",
            width: 120,
            width: 165
          },

          {
            name: 'MaxLoanAmt',
            label: 'MaxLoanAmount',
            width: 165,
            sorttype: 'number',
            align: "right",
            search: false,
            formatter: 'currency',
            formatoptions: {
              prefix: " $",
              suffix: " "
            }
          }

        ],
        additionalProperties: ["Symbol", "Description"],
        subGrid: true,
        subGridRowExpanded: function (subgridDivId, rowid) {
            var item = $(this).jqGrid("getLocalRow", rowid);
            $("#" + $.jgrid.jqID(subgridDivId)).html("Symbol: <em>" + item.Symbol +
                "</em><br/>Description: <em>" + item.Description + "</em>");
        },
        beforeProcessing: function (data) {
            var symbolsMap = {}, symbolsValues = ":All", rows = data.rows, i, symbol;
            for (i = 0; i < rows.length; i++) {
                symbol = rows[i].Symbol;
                if (!symbolsMap.hasOwnProperty(symbol)) {
                    symbolsMap[symbol] = 1;
                    symbolsValues += ";" + symbol + ":" + symbol;
                }
            }
            $(this).jqGrid("setColProp", 'Symbol', {
                stype: "select",
                searchoptions: {
                    value: symbolsValues
                }
            }).jqGrid('destroyFilterToolbar')
            .jqGrid('filterToolbar', {
                stringResult: true,
                searchOnEnter: false,
                defaultSearch : "cn"
            });
        },
        /*beforeProcessing: function (data) {
            var item, i, n = data.length;
            for (i = 0; i < n; i++) {
                item = data[i];
                item.Quantity = parseFloat($.trim(item.Quantity).replace(",", ""));
                item.LTVRatio = parseFloat($.trim(item.LTVRatio *10000).replace(",", ""));
                item.Value = parseFloat($.trim(item.Value).replace(",", ""));
                item.Num1 = parseInt($.trim(item.Num1).replace(",", ""), 10);
                item.Num2 = parseInt($.trim(item.Num2).replace(",", ""), 10);
            }
        }, */
        iconSet: "fontAwesome",
        loadonce: true,
        rownumbers: true,
        cmTemplate: {
          autoResizable: true,
          editable: true
        },
        autoResizing: {
          compact: true
        },
        autowidth: true,
        height: 'auto',
        forceClientSorting: true,
        sortname: "Symbol",
        footerrow: true,
        caption: "<b>Collateral Value</b> <span class='pull-right' style='margin-right:20px;'>Valuation as of: " + mmddyyyy + "</span>",
        loadComplete: function() {
          var $self = $(this),
            sum = $self.jqGrid("getCol", "Price", false, "sum"),
            sum1 = $self.jqGrid("getCol", "MaxLoanAmt", false, "sum");
          //ltvratio =  $self.jqGrid("getCol","LTVRatio:addas", "Aved Loan Amount");
          $self.jqGrid("footerData", "set", {
            LTVCategory: "Max Approved Loan Amount:",
            Price: sum,
            MaxLoanAmt: sum1
          });
        }
      });

      $("#output").jqGrid('filterToolbar', {stringResult: true, searchOnEnter: false, defaultSearch : "cn"});

        $(window).on("resize", function () {
            var newWidth = $("#output").closest(".ui-jqgrid").parent().width();
            $("#output").jqGrid("setGridWidth", newWidth, true);
        }).triggerHandle("resize");
    });

【问题讨论】:

    标签: json ajax jqgrid


    【解决方案1】:

    没有将 jqgrid 数据导出为 pdf 的内置方法。您必须使用第三方工具(我个人喜欢 iTextSharp,可以从 Here 下载。您必须创建用于在控制器中打印网格数据的操作方法。

    Here 也是一个人做的另一个例子。

    Here 也是 trirand 中的另一个例子。如果您看到他们使用 iTextHsarp 的源代码。 使用 System.Collections.Generic; 使用 System.Linq; 使用 System.Web; 使用 System.Web.Mvc; 使用 JQGridMVCExamples.Models; 使用 Trirand.Web.Mvc; 使用 System.IO;

    // 
    // For PDF export we are using the free open-source iTextSharp library.
    //
    using iTextSharp.text;
    using iTextSharp.text.pdf;
    using System.Data;
    
    
    namespace JQGridMVCExamples.Controllers.Grid
    {
        public partial class GridController : Controller
        {
            // This is the default action for the View. Use it to setup your grid Model.
            public ActionResult ExportPDF()
            {
                // Get the model (setup) of the grid defined in the /Models folder.
                var gridModel = new OrdersJqGridModel();
                var ordersGrid = gridModel.OrdersGrid;
    
                // Setting the DataUrl to an action (method) in the controller is required.
                // This action will return the data needed by the grid
                ordersGrid.DataUrl = Url.Action("PDFGrid_DataRequested");
    
                // customize the default Orders grid model with custom settings
                // NOTE: you need to call this method in the action that fetches the data as well,
                // so that the models match
                SetPDFExportGrid(ordersGrid);
    
                // Pass the custmomized grid model to the View
                return View(gridModel);
            }
    
            // This method is called when the grid requests data        
            public JsonResult PDFGrid_DataRequested()
            {
                // Get both the grid Model and the data Model
                // The data model in our case is an autogenerated linq2sql database based on Northwind.
                var gridModel = new OrdersJqGridModel();
                var northWindModel = new NorthwindDataContext();
    
                // customize the default Orders grid model with our custom settings
                SetPDFExportGrid(gridModel.OrdersGrid);
    
                // Save the current grid state in Session
                // We will later need it for PDF Export
                JQGridState gridState = gridModel.OrdersGrid.GetState();
                Session["gridState"] = gridState;
    
                // return the result of the DataBind method, passing the datasource as a parameter
                // jqGrid for ASP.NET MVC automatically takes care of paging, sorting, filtering/searching, etc
    
                return gridModel.OrdersGrid.DataBind(northWindModel.Orders);
            }
    
            public JsonResult PDFExport_AutoCompleteShipName(string term)
            {
                var northWindModel = new NorthwindDataContext();
                JQAutoComplete autoComplete = new JQAutoComplete();
    
                autoComplete.DataField = "ShipName";
                autoComplete.AutoCompleteMode = AutoCompleteMode.BeginsWith;
                autoComplete.DataSource = from o in northWindModel.Orders
                                          select o;
                return autoComplete.DataBind();
            }
    
            private void SetPDFExportGrid(JQGrid ordersGrid)
            {
                // show the search toolbar
                ordersGrid.ToolBarSettings.ShowSearchToolBar = true;
                ordersGrid.ToolBarSettings.ShowSearchButton = true;
    
                var orderDateColumn = ordersGrid.Columns.Find(c => c.DataField == "OrderDate");
                orderDateColumn.DataFormatString = "{0:yyyy/MM/dd}";
                orderDateColumn.SearchType = SearchType.DatePicker;
                orderDateColumn.DataType = typeof(DateTime);
                orderDateColumn.SearchControlID = "DatePicker";
                orderDateColumn.SearchToolBarOperation = SearchOperation.IsEqualTo;
    
                var shipNameColumn = ordersGrid.Columns.Find(c => c.DataField == "ShipName");
                shipNameColumn.SearchType = SearchType.AutoComplete;
                shipNameColumn.DataType = typeof(string);
                shipNameColumn.SearchControlID = "AutoComplete";
                shipNameColumn.SearchToolBarOperation = SearchOperation.Contains;
    
                var orderIDColumns = ordersGrid.Columns.Find(c => c.DataField == "OrderID");
                orderIDColumns.Searchable = true;
                orderIDColumns.DataType = typeof(int);
                orderIDColumns.SearchToolBarOperation = SearchOperation.IsEqualTo;
    
                SetPDFCustomerIDSearchDropDown(ordersGrid);
                SetPDFFreightSearchDropDown(ordersGrid);
            }
    
            private void SetPDFCustomerIDSearchDropDown(JQGrid ordersGrid)
            {
                // setup the grid search criteria for the columns
                JQGridColumn customersColumn = ordersGrid.Columns.Find(c => c.DataField == "CustomerID");
                customersColumn.Searchable = true;
    
                // DataType must be set in order to use searching
                customersColumn.DataType = typeof(string);
                customersColumn.SearchToolBarOperation = SearchOperation.IsEqualTo;
                customersColumn.SearchType = SearchType.DropDown;
    
                // Populate the search dropdown only on initial request, in order to optimize performance
                if (ordersGrid.AjaxCallBackMode == AjaxCallBackMode.RequestData)
                {
                    var northWindModel = new NorthwindDataContext();
                    var searchList = from customers in northWindModel.Customers
                                     select new SelectListItem
                                     {
                                         Text = customers.CustomerID,
                                         Value = customers.CustomerID
                                     };
    
                    customersColumn.SearchList = searchList.ToList<SelectListItem>();
                    customersColumn.SearchList.Insert(0, new SelectListItem { Text = "All", Value = "" });
                }
            }
    
            private void SetPDFFreightSearchDropDown(JQGrid ordersGrid)
            {
                // setup the grid search criteria for the columns
                JQGridColumn freightColumn = ordersGrid.Columns.Find(c => c.DataField == "Freight");
                freightColumn.Searchable = true;
    
                // DataType must be set in order to use searching
                freightColumn.DataType = typeof(decimal);
                freightColumn.SearchToolBarOperation = SearchOperation.IsGreaterOrEqualTo;
                freightColumn.SearchType = SearchType.DropDown;
    
                // Populate the search dropdown only on initial request, in order to optimize performance
                if (ordersGrid.AjaxCallBackMode == AjaxCallBackMode.RequestData)
                {
                    List<SelectListItem> searchList = new List<SelectListItem>();
                    searchList.Add(new SelectListItem { Text = "> 10", Value = "10" });
                    searchList.Add(new SelectListItem { Text = "> 30", Value = "30" });
                    searchList.Add(new SelectListItem { Text = "> 50", Value = "50" });
                    searchList.Add(new SelectListItem { Text = "> 100", Value = "100" });
    
                    freightColumn.SearchList = searchList.ToList<SelectListItem>();
                    freightColumn.SearchList.Insert(0, new SelectListItem { Text = "All", Value = "" });
                }
            }
    
            public ActionResult ExportToPDF(string exportType)
            {            
                var gridModel = new OrdersJqGridModel();
                var northWindModel = new NorthwindDataContext();
                var grid = gridModel.OrdersGrid;
    
                // Get the last grid state the we saved before in Session in the DataRequested action
                JQGridState gridState = Session["GridState"] as JQGridState;
    
                // Need to set grid options again
                SetExportGrid(grid);
    
                if (String.IsNullOrEmpty(exportType))
                    exportType = "1";
    
                DataTable exportData;
                switch (exportType)
                {
                    case "1":
                        grid.ExportSettings.ExportDataRange = ExportDataRange.All;
                        exportData = grid.GetExportData(northWindModel.Orders);
                        ExportToPDF(exportData);
                        break;
                    case "2":
                        grid.ExportSettings.ExportDataRange = ExportDataRange.Filtered;
                        exportData = grid.GetExportData(northWindModel.Orders, gridState);
                        ExportToPDF(exportData);
                        break;
                    case "3":
                        grid.ExportSettings.ExportDataRange = ExportDataRange.FilteredAndPaged;
                        exportData = grid.GetExportData(northWindModel.Orders, gridState);
                        ExportToPDF(exportData);
                        break;
                }
    
                return View();
            }
    
            private void ExportToPDF(DataTable dt)
            {
                // 
                // For PDF export we are using the free open-source iTextSharp library.
                //
    
                Document pdfDoc = new Document();
                MemoryStream pdfStream = new MemoryStream();
                PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, pdfStream);
    
                pdfDoc.Open();//Open Document to write
                pdfDoc.NewPage();
    
                Font font8 = FontFactory.GetFont("ARIAL", 7);
    
                PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
                PdfPCell PdfPCell = null;
    
                //Add Header of the pdf table
                for (int column = 0; column < dt.Columns.Count; column++)
                {
                    PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Columns[column].Caption, font8)));
                    PdfTable.AddCell(PdfPCell);
                }
    
                //How add the data from datatable to pdf table
                for (int rows = 0; rows < dt.Rows.Count; rows++)
                {
                    for (int column = 0; column < dt.Columns.Count; column++)
                    {
                        PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
                        PdfTable.AddCell(PdfPCell);
                    }
                }
    
                PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table            
                pdfDoc.Add(PdfTable); // add pdf table to the document
                pdfDoc.Close();
                pdfWriter.Close();
    
                Response.ClearContent();
                Response.ClearHeaders();
                Response.ContentType = "application/pdf";
                Response.AppendHeader("Content-Disposition", "attachment; filename=gridexport.pdf");
                Response.BinaryWrite(pdfStream.ToArray());
                Response.End();
            }
        }
    }
    

    【讨论】:

    • 我没有使用 JAVA 或 .NET。我正在使用 JavaScript 和 JSON 创建 JQgrid 表。有没有办法使用 JQgrid 或任何第三方 API 从客户端创建 PDF 和 excel 文件,我可以使用它来基于 jqgrid 表生成 pdf 和 excel 文件?
    • 您可以使用 Answer 来了解如何仅使用 javascript 来完成。