编辑gridview excel导出

时间:2016-04-29 20:09:47

标签: c# wpf mvvm telerik

我目前实现了一种方法,它可以导出excel任何作为参数传递的RadGridView。它导出完全正常,我想通过在excel文件的第一行添加Title然后在该行下面追加RadGridView来增强它。请问是否有人知道我应该怎么做?

public static void Export(RadGridView grid)
{
    const string extension = "xls";

    var dialog = new SaveFileDialog
    {
        DefaultExt = extension,
        Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, "Excel"),
        FilterIndex = 1
    };

    if (dialog.ShowDialog() != true)
    {
        return;
    }

    using (var stream = dialog.OpenFile())
    {
        var exportOptions = new GridViewExportOptions
        {
            Format = ExportFormat.ExcelML,
            ShowColumnHeaders = true,
            ShowColumnFooters = true,
            ShowGroupFooters = false,
        };
        exportOptions.Items = (IEnumerable)grid.ItemsSource;
        grid.Export(stream, exportOptions);
    }
}

1 个答案:

答案 0 :(得分:0)

如果有兴趣的话。这是我使用的解决方案,

public static void ExportWithHeader(RadGridView grid, string header)
{
    try
    {
        string extension = "xls";
        SaveFileDialog dialog = new SaveFileDialog()
        {
            DefaultExt = extension,
            Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, "Excel"),
            FilterIndex = 1,
            FileName = header
        };
        if (dialog.ShowDialog() == true)
        {
            using (Stream stream = dialog.OpenFile())
            {
                MemoryStream ms = new MemoryStream();
                grid.Export(
                    ms,
                    new GridViewExportOptions()
                    {
                        Format = ExportFormat.ExcelML,
                        ShowColumnHeaders = true,
                        ShowColumnFooters = true,
                        ShowGroupFooters = false,
                    });
                ms.Seek(0, SeekOrigin.Begin);
                header = String.Format(
                    "<Row><Cell  ss:Index='1'><Data ss:Type='String'>{0}</Data></Cell></Row>", header);
                StreamReader sr = new StreamReader(ms);
                string msStr = sr.ReadToEnd();
                msStr = msStr.Insert(msStr.IndexOf("<Row>"), header);                    
                stream.Write(Encoding.UTF8.GetBytes(msStr), 0, msStr.Length);
            }

            Process.Start(dialog.FileName);
        }
    }
    catch
    {
        Notification.Error("Process Busy", "Please exit excel instance.");
    }
}