1. 程式人生 > 實用技巧 >Dev Express WPF GridControl 資料匯出到Excel

Dev Express WPF GridControl 資料匯出到Excel

Dev Express WPF 給控制元件提供了公共的匯出方法:

以匯出資料到Excel表格為例:

匯出模式分為兩種型別:Data-Aware Export WYSIWYG Export

其中WYSIWYG Export 模式支援匯出結果保持GridControl設定的 PrintStyle,但在Excel中顯示有寫問題,同時效能也稍差一些,可能這是Dev 升級匯出引擎的部分原因吧。

Data-Aware Export 模型匯出資料則不支援PrintStyle,如果需要設定表格資料的展示樣式,可以實現CustomizeCell 事件;

測試程式碼:

<Window x:Class="GridExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"       
        xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors
" xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid" xmlns:local="clr-namespace:GridExample" Width="600" Height="350" > <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="
/GridExample;component/Themes/PrintCellStylesWPF.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources> <Grid VerticalAlignment="Top"> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <dxg:GridControl Name="grid" AutoGenerateColumns="AddNew"> <dxg:GridControl.Columns> <dxg:GridColumn FieldName="PlainText"/> <dxg:GridColumn FieldName="MemoText" PrintCellStyle="{StaticResource MemoColumnPrintingStyle}" > <dxg:GridColumn.EditSettings> <dxe:MemoEditSettings/> </dxg:GridColumn.EditSettings> </dxg:GridColumn> <dxg:GridColumn FieldName="BooleanMember" PrintCellStyle="{StaticResource CheckEditColumnPrintingStyle}" > <dxg:GridColumn.EditSettings> <dxe:CheckEditSettings/> </dxg:GridColumn.EditSettings> </dxg:GridColumn> <dxg:GridColumn FieldName="Image" PrintCellStyle="{StaticResource ImageColumnPrintingStyle}" > <dxg:GridColumn.EditSettings> <dxe:PopupImageEditSettings/> </dxg:GridColumn.EditSettings> </dxg:GridColumn> </dxg:GridControl.Columns> <dxg:GridControl.View> <dxg:TableView Name="view" PrintColumnHeaderStyle="{StaticResource HeaderStyle}"/> </dxg:GridControl.View> </dxg:GridControl> <Button Grid.Row="1" Width="150" Name="PrintButton" Click="PrintButton_Click" Content="Show print preview"/> </Grid> </Window>
View Code

// Developer Express Code Central Example:
// How to use the PrintCellStyle property to customize cell's printing appearance
// 
// This example shows how to create custom PrintCellStyle for grid columns to bring
// a custom printing appearance for PopupImageEdit, CheckBoxEdit and MemoEdit.
// 
// You can find sample updates and versions for different programming languages here:
// http://www.devexpress.com/example=E3227

using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Collections.Generic;
using System.Windows.Resources;
using System.IO;
using System.Drawing;
using System.Windows.Data;
using DevExpress.XtraPrinting;
using DevExpress.Export;

namespace GridExample {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();

            Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e) {
            grid.ItemsSource = new List<TestData>() {
                new TestData() { PlainText = "LMA AG", MemoText = "Mercedes-Benz SLK \n 2004 \n Silver", BooleanMember = true, Image = GetImage("/Images/1.png") },
                new TestData() { PlainText = "Western Motors", MemoText ="Rolls-Royce Corniche \n 1975 \n Snowy whight", BooleanMember = false, Image = GetImage("/Images/2.png") },
                new TestData() { PlainText = "Sun car rent", MemoText = "Ford Ranger FX-4\n 1999 \n Red rock", BooleanMember = true, Image = GetImage("/Images/3.png") }
            };
        }

        ImageSource GetImage(string path) {
            return new BitmapImage(new Uri(path, UriKind.Relative));
        }

        private void PrintButton_Click(object sender, RoutedEventArgs e) {
            //view.ExportToCsv(@"C:\Users\lenovo\Desktop\testExport\aa.csv");
            view.ExportToXlsx(@"C:\Users\lenovo\Desktop\testExport\aa.xlsx", new XlsxExportOptionsEx 
            { ExportType = ExportType.WYSIWYG
            });
            XlsxExportOptionsEx options = new XlsxExportOptionsEx();
            options.CustomizeCell += Options_CustomizeCell;
            view.ExportToXlsx(@"C:\Users\lenovo\Desktop\testExport\aa11.xlsx", options);
            view.ShowPrintPreview(this);
        }

        private void Options_CustomizeCell(CustomizeCellEventArgs e)
        {
            if(e.AreaType == SheetAreaType.Header)
            {
                e.Formatting.Font = new DevExpress.Export.XlCellFont { Name= "微軟雅黑", Bold = true, Size = 20 };
                e.Formatting.BackColor = System.Drawing.Color.Pink;
                e.Handled = true;
            }
        }
    }
}
View Code

PrintStyle 設定

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
                    xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors"
                    xmlns:dxp="http://schemas.devexpress.com/winfx/2008/xaml/printing"
                    xmlns:dxgt="clr-namespace:DevExpress.Xpf.Grid.Themes;assembly=DevExpress.Xpf.Grid.v20.1"
                    >
    <Style x:Key="HeaderStyle"  
       TargetType="{x:Type dxe:TextEdit}"  
       BasedOn="{StaticResource {dxgt:TableViewThemeKey ResourceKey=DefaultPrintCellStyle}}">
        <Setter Property="dxp:ExportSettings.TargetType" Value="Text" />
        <Setter Property="FontSize" Value="11pt" />
        <Setter Property="FontFamily" Value="Calibri" />
        <Setter Property="Background" Value="#177477" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="FontWeight" Value="Bold" />
    </Style>
    
    <Style x:Key="ImageColumnPrintingStyle" 
           TargetType="{x:Type dxe:PopupImageEdit}"
           BasedOn="{StaticResource {dxgt:TableViewThemeKey ResourceKey=DefaultPrintCellStyle}}">
        <Setter Property="dxp:ExportSettings.TargetType" Value="Panel" />
        <Setter Property="DisplayTemplate">
            <Setter.Value>
                <ControlTemplate TargetType="dxe:PopupImageEdit">

                    <dxe:ImageEdit Source="{Binding Path=Value}"
                                    IsPrintingMode="True" 
                                    Margin="4" 
                                    HorizontalAlignment="Center" 
                                    VerticalAlignment="Center"       
                                    />

                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <dx:BoolToObjectConverter x:Key="BoolToTextConverter" TrueValue="Avaliable" FalseValue="NotAvaliable" />

    <Style x:Key="CheckEditColumnPrintingStyle" 
           TargetType="dxe:CheckEdit"
           BasedOn="{StaticResource {dxgt:TableViewThemeKey ResourceKey=DefaultPrintCellStyle}}">
        <Style.Setters>
            <Setter Property="dxp:ExportSettings.TargetType" Value="Panel" />
            <Setter Property="DisplayTemplate">
                <Setter.Value>
                    <ControlTemplate TargetType="dxe:CheckEdit">
                        <dxe:TextEdit Text="{Binding Path=Value, Converter={StaticResource BoolToTextConverter}}" HorizontalAlignment="Center" Margin="4"
                                          />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style.Setters>
    </Style>

    <Style x:Key="MemoColumnPrintingStyle" 
           TargetType="dxe:MemoEdit"
           BasedOn="{StaticResource {dxgt:TableViewThemeKey ResourceKey=DefaultPrintCellStyle}}">
        <Style.Setters>
            <Setter Property="dxp:ExportSettings.TargetType" Value="Panel" />
            <Setter Property="DisplayTemplate">
                <Setter.Value>
                    <ControlTemplate TargetType="dxe:MemoEdit">
                        <dxe:TextEdit Text="{Binding Value}"
                                          TextWrapping="Wrap"
                                          IsPrintingMode="True"
                                          Margin="4"
                                          VerticalContentAlignment="Center"
                                          HorizontalContentAlignment="Left"
                                          />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style.Setters>
    </Style>
</ResourceDictionary>
View Code

    public class TestData {
        public string PlainText { get; set; }
        public string MemoText { get; set; }
        public bool BooleanMember { get; set; }
        public ImageSource Image { get; set; }
    }
View Code

Demo