【问题标题】:Kendo Grid print all data to excel, not just visible dataKendo Grid 将所有数据打印到 Excel,而不仅仅是可见数据
【发布时间】:2014-08-28 16:36:51
【问题描述】:

假设我有 80 个项目的网格,页面大小为 10,当从控制器打印时,我想打印所有数据,而不仅仅是第一页上的可见数据。

我有来自 Telerik 的优秀“Export Grid to Excel”测试项目,并且我已经将导出功能全部覆盖,并且工作起来就像一个魅力。基本上只包含 NPOI 文件并开始使用它。

有没有办法让我从 DataSourceRequest 中迭代所有产品数据?

我的代码示例:

public FileResult Export([DataSourceRequest]DataSourceRequest request)
{
//Get the data representing the current grid state - page, sort and filter
IEnumerable products = db.Products.ToDataSourceResult(request).Data;


//TODO: Get all data but not just the data from the visible page as above!!!


//Create new Excel workbook
var workbook = new HSSFWorkbook();

//Create new Excel sheet
var sheet = workbook.CreateSheet();

//(Optional) set the width of the columns
sheet.SetColumnWidth(0, 10 * 256);
sheet.SetColumnWidth(1, 50 * 256);
sheet.SetColumnWidth(2, 50 * 256);
sheet.SetColumnWidth(3, 50 * 256);

//Create a header row
var headerRow = sheet.CreateRow(0);

//Set the column names in the header row
headerRow.CreateCell(0).SetCellValue("Product ID");
headerRow.CreateCell(1).SetCellValue("Product Name");
headerRow.CreateCell(2).SetCellValue("Unit Price");
headerRow.CreateCell(3).SetCellValue("Quantity Per Unit");

//(Optional) freeze the header row so it is not scrolled
sheet.CreateFreezePane(0, 1, 0, 1);

int rowNumber = 1;

//Populate the sheet with values from the grid data
foreach (Product product in products)
{
    //Create a new row
    var row = sheet.CreateRow(rowNumber++);

    //Set values for the cells
    row.CreateCell(0).SetCellValue(product.ProductID);
    row.CreateCell(1).SetCellValue(product.ProductName);
    row.CreateCell(2).SetCellValue(product.UnitPrice.ToString());
    row.CreateCell(3).SetCellValue(product.QuantityPerUnit.ToString());
}

//Write the workbook to a memory stream
MemoryStream output = new MemoryStream();
workbook.Write(output);

//Return the result to the end user

return File(output.ToArray(),   //The binary data of the XLS file
    "application/vnd.ms-excel", //MIME type of Excel files
    "GridExcelExport.xls");     //Suggested file name in the "Save as" dialog which will be displayed to the end user

}

【问题讨论】:

  • 所以你不想使用分页,但你想使用过滤?
  • 嗯,实际上是的@Stef。但我希望能够打印带有完整数据的 excel 表。但是,如果用户对列进行了重新排序、对列进行了排序或对网格进行了任何操作,那么我希望将其感染到控制器中的 excel 创建中,因此我也需要过滤:/

标签: c# excel kendo-ui telerik kendo-grid


【解决方案1】:

DataSourceRequest 类的来源可以在here 找到。

如果你禁用分页属性,你可能会得到所有过滤+排序的数据:

public FileResult Export([DataSourceRequest]DataSourceRequest request)
{
  request.Take = 9999999;
  request.Skip = 0;

  // Get the data representing the current grid state : sort and filter
  IEnumerable products = db.Products.ToDataSourceResult(request).Data;

【讨论】:

    【解决方案2】:

    一段时间后,我偶然发现了一个有效的答案。 @Stef 的回答让我走上了正确的道路,尽管我实际上并没有使用他的回答,因此我会提高他的回答以寻求帮助。我找到了一种计算页数的方法,然后简单地编辑了每一页的 DataSourceRequest。这种方式可以确保我获得数据库中的所有页面。我希望这对将来的其他人有所帮助:)

    public FileResult Export([DataSourceRequest]DataSourceRequest request)
    {
    //Count pages to use as iterator when adding to list
    var pages = db.Products.ToDataSourceResult(request).Total/request.PageSize;
    
    //Get the data representing the current grid state - page, sort and filter
    //IEnumerable products = db.Products.ToDataSourceResult(request).Data;
    
    //Get the data representing the current grid state - page, sort and filter
    var products = new List<Product>();
    
    //To ensure all pages get fetched from db
    for (int i = 1; i < pages + 1; i++)
    {
        request.Page = i;
        IEnumerable prod = db.Products.ToDataSourceResult(request).Data;
        products.AddRange(prod.Cast<Product>().ToList());
    }
    
    //Create new Excel workbook
    var workbook = new HSSFWorkbook();
    
    //Create new Excel sheet
    var sheet = workbook.CreateSheet();
    
    //(Optional) set the width of the columns
    sheet.SetColumnWidth(0, 10 * 256);
    sheet.SetColumnWidth(1, 50 * 256);
    sheet.SetColumnWidth(2, 50 * 256);
    sheet.SetColumnWidth(3, 50 * 256);
    
    //Create a header row
    var headerRow = sheet.CreateRow(0);
    
    //Set the column names in the header row
    headerRow.CreateCell(0).SetCellValue("Product ID");
    headerRow.CreateCell(1).SetCellValue("Product Name");
    headerRow.CreateCell(2).SetCellValue("Unit Price");
    headerRow.CreateCell(3).SetCellValue("Quantity Per Unit");
    
    //(Optional) freeze the header row so it is not scrolled
    sheet.CreateFreezePane(0, 1, 0, 1);
    
    int rowNumber = 1;
    
    //Populate the sheet with values from the grid data
    foreach (Product product in products)
    {
        //Create a new row
        var row = sheet.CreateRow(rowNumber++);
    
        //Set values for the cells
        row.CreateCell(0).SetCellValue(product.ProductID);
        row.CreateCell(1).SetCellValue(product.ProductName);
        row.CreateCell(2).SetCellValue(product.UnitPrice.ToString());
        row.CreateCell(3).SetCellValue(product.QuantityPerUnit.ToString());
    }
    
    //Write the workbook to a memory stream
    MemoryStream output = new MemoryStream();
    workbook.Write(output);
    
    //Return the result to the end user
    
    return File(output.ToArray(),   //The binary data of the XLS file
        "application/vnd.ms-excel", //MIME type of Excel files
        "GridExcelExport.xls");     //Suggested file name in the "Save as" dialog which will be displayed to the end user
    }
    

    【讨论】:

    • 谢谢。当行数小于页面大小时,此代码中似乎存在错误,您不会返回任何行。例如,如果页面大小为 10,并且只有 1 行,Total / PageSize 被评估为 0,因此将跳过 for 循环。
    • @RamiA。好点子。您当然可以在划分之前检查 Total 是否小于 Pagesize,然后您只需将其设置为 1 或类似的值;)
    【解决方案3】:

    您可以使用 javascript 将所有数据打印到 excel 中,如下所示

    function ExportToCSV() {
    
             var dataSource = $("#grid").data("kendoGrid").dataSource;
             var filteredDataSource = new kendo.data.DataSource({
                 data: dataSource.data(),
                 filter: dataSource.filter()
             });
    
             filteredDataSource.read();
             var data = filteredDataSource.view();
    
             var result = "data:application/vnd.ms-excel,";
    
             result += "<table><tr><th>ProductID</th><th>ProductName</th><th>UnitPrice</th><th>Discontinued</th><th>UnitsInStock</th><th>Category</th></tr>";
    
             for (var i = 0; i < data.length; i++) {
                 result += "<tr>";
    
                 result += "<td>";
                 result += data[i].ProductID;
                 result += "</td>";
    
                 result += "<td>";
                 result += data[i].ProductName;
                 result += "</td>";
    
                 ..
    
                 result += "</tr>";
             }
    
                 result += "</table>";
                 if (window.navigator.msSaveBlob) {
                     window.navigator.msSaveBlob(new Blob([result]), 'export.xls');
                 } else {
                     window.open(result);
                 }
    
    
                 e.preventDefault();
             }
    

    希望这会有所帮助

    【讨论】:

    • 感谢@AbbasGaliyakot,但您的方法可以很好地打印第一页,但不能打印其他页面的数据。
    猜你喜欢
    • 2014-09-23
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多