WPF控件保存为图片
<MetroChart:ClusteredBarChart Name="PerformanceChart" ChartTitle="员工绩效" ChartSubTitle="流出流入绩效" FontSize="14" SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}" SeriesSource="{Binding Path=Series}" IsRowColumnSwitched="True" > <MetroChart:ClusteredBarChart.Resources> <ResourceDictionary Source="pack://application:,,,/De.TorstenMandelkow.MetroChart;component/Themes/Generic.xaml"/> </MetroChart:ClusteredBarChart.Resources> <MetroChart:ClusteredBarChart.SeriesTemplate> <DataTemplate> <MetroChart:ChartSeries SeriesTitle="{Binding Path=DisplayName}" DisplayMember="Performer" ValueMember="Score" ItemsSource="{Binding Path=Items}" /> </DataTemplate> </MetroChart:ClusteredBarChart.SeriesTemplate> </MetroChart:ClusteredBarChart>
Size size = new Size(this.Width, this.Height); PerformanceChart.Measure(size); var rtb = new RenderTargetBitmap( (int)PerformanceChart.ActualWidth, //width (int)PerformanceChart.ActualHeight, //height 96, //dpi x 96, //dpi y PixelFormats.Pbgra32 // pixelformat ); rtb.Render(PerformanceChart); var bitmap = rtb; byte[] data; System.Windows.Media.Imaging.JpegBitmapEncoder encoder = new System.Windows.Media.Imaging.JpegBitmapEncoder(); encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmap)); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { encoder.Save(ms); data = ms.ToArray(); } NPOI.HSSF.UserModel.HSSFWorkbook workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(); var sheet = workbook.CreateSheet(); var row = sheet.CreateRow(0); var cell = row.CreateCell(0); cell.SetCellValue("Hello world"); row = sheet.CreateRow(1); cell = row.CreateCell(0); int pictureIdx = workbook.AddPicture(data, NPOI.SS.UserModel.PictureType.PNG); NPOI.HSSF.UserModel.HSSFPatriarch patriarch = (NPOI.HSSF.UserModel.HSSFPatriarch)sheet.CreateDrawingPatriarch(); var rowsNum = 1; //add a picture NPOI.HSSF.UserModel.HSSFClientAnchor anchor = new NPOI.HSSF.UserModel.HSSFClientAnchor(0, 10, 1023, 0, 0, rowsNum, 2, rowsNum); NPOI.HSSF.UserModel.HSSFPicture pict = (NPOI.HSSF.UserModel.HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx); pict.Resize(); var dlg = new Microsoft.Win32.SaveFileDialog { Filter = ".xls files|*.xls", DefaultExt = ".xls" }; var path = dlg.ShowDialog(this).Value ? dlg.FileName : null; if (path != null) { using (System.IO.FileStream fs = new System.IO.FileStream(dlg.FileName, System.IO.FileMode.OpenOrCreate)) { //将内容写入到硬盘中 workbook.Write(fs); } } System.Windows.MessageBox.Show("导出成功!");