Tuesday, January 3, 2017

Customize Excel export from Kendo UI MVC grid

@(Html.Kendo().Grid()
    .Name(gridId)
    .Excel(excel => excel.FileName(@filename))
    .Events(e => e.ExcelExport("excelExport"))
)

javascript:
    function excelExport(e) {
        var sheet = e.workbook.sheets[0];

        var row1 = sheet.rows[0];
        for (var col = 0; col < 2; col++) {
            row1.cells[col].background = "#0D68C8";
            row1.cells[col].color = "#FFFFFF";
            row1.cells[col].bold = "true";
            row1.cells[col].hAlign = "center";
        }

        var row2 = sheet.rows[1];
        for (var col = 0; col < 3; col++) {
            row2.cells[col].background = "#0D68C8";
            row2.cells[col].color = "#FFFFFF";
            row2.cells[col].bold = "true";
            row2.cells[col].hAlign = "right";
        }

        for (var rowIndex = 2; rowIndex < sheet.rows.length; rowIndex++) {
            var row = sheet.rows[rowIndex];
            for (var col = 1; col <= 3; col++) {
                row.cells[col].format = "#,###";
            }
            for (var col = 0; col <= 3; col++) {
                if (rowIndex % 2 == 0) {
                    row.cells[col].background = "#ececec";
                }
                else {
                    row.cells[col].background = "#aabbcc";
                }
            }
        }

        //var formula = "=D{0}-D{1}".format(sheet.rows.length + 2, sheet.rows.length);
        sheet.rows.push(
            {
                cells: [
                ]
            },
            {
                height: 40,
                cells: [
                    { value: "" },
                    { value: "" },
                    { value: "US Pru Phase 2 IM Threshold", color: "#FF0000", wrap: true },
                    { value: 2250000000000, format : "#,###", color: "#FF0000", vAlign: "center" }
                ]
            },
            {
                cells: [
                ]
            },
            {
                cells: [
                    { value: "" },
                    { value: "" },
                    { value: "Under/Over Amount" },
                    //{ formula: "=R[-2]C-R[-4]C", format: "#,##0_);[Red](#,##0)" }
                    { formula: "=D{0}-D{1}".format(sheet.rows.length + 2, sheet.rows.length), format: "#,##0_);[Red](#,##0)" }
                ]
            }
        );

    }

end of javascript