在导出网格数据时获取数字类型字段在EXCEL中

时间:2014-05-27 11:56:00

标签: c# asp.net kendo-grid export-to-excel

我正在将一个Kendo网格导出到EXCEL。使用DocumentFormat.OpenXml.Below是我正在使用的ExportToExcel()操作。

当我正在导出它运行良好但是“数字字段”在EXCEl中显示为字符串。由于某种原因,我必须在数字中包含数据值(如果它是数字字段)/字符串,如果它在网格中是字符串类型

有没有办法实现这个?

请帮助我任何人。

    public JsonResult ExportToExcel(string model, string data, string title)
    {
        using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
        {
            /* Create the worksheet. */

            SpreadsheetDocument spreadsheet = Excel.CreateWorkbook(stream);
            Excel.AddBasicStyles(spreadsheet);
            Excel.AddAdditionalStyles(spreadsheet);
            Excel.AddWorksheet(spreadsheet, title);
            Worksheet worksheet = spreadsheet.WorkbookPart.WorksheetParts.First().Worksheet;


            /* Get the information needed for the worksheet */

            var modelObject = JsonConvert.DeserializeObject<dynamic>(model);
            var dataObject = JsonConvert.DeserializeObject<dynamic>(data);


            /* Add the column titles to the worksheet. */

            // For each column...
            for (int mdx = 0; mdx < modelObject.Count; mdx++)
            {
                // If the column has a title, use it.  Otherwise, use the field name.
                Excel.SetColumnHeadingValue(spreadsheet, worksheet, Convert.ToUInt32(mdx + 1),
                    modelObject[mdx].title == null ? modelObject[mdx].field.ToString() : modelObject[mdx].title.ToString(),
                    false, false);

                // Is there are column width defined?
                Excel.SetColumnWidth(worksheet, mdx + 1, modelObject[mdx].width != null
                    ? Convert.ToInt32(modelObject[mdx].width.ToString()) / 4
                    : 25);
            }


            /* Add the data to the worksheet. */

            // For each row of data...
            for (int idx = 0; idx < dataObject.Count; idx++)
            {
                // For each column...
                for (int mdx = 0; mdx < modelObject.Count; mdx++)
                {
                    // Set the field value in the spreadsheet for the current row and column.
                    Excel.SetCellValue(spreadsheet, worksheet, Convert.ToUInt32(mdx + 1), Convert.ToUInt32(idx + 2),
                        dataObject[idx][modelObject[mdx].field.ToString()].ToString(),
                        false, false);
                }
            }


            /* Save the worksheet and store it in Session using the spreadsheet title. */

            worksheet.Save();
            spreadsheet.Close();
            byte[] file = stream.ToArray();
            Session[title] = file;
        }

        return Json(new { success = true }, JsonRequestBehavior.AllowGet);
    }

1 个答案:

答案 0 :(得分:0)

我正在使用EPPlus从Kendo网格生成Excel导出。

有关详细信息,请参阅this file中的 public JsonResult Export(KendoGridFilter过滤器,字符串guid)方法。