Silverlight下“DataGrid”和“Pdf”导出
首先,Silverlight下的“DataGrid”控件多少让人有些失望,它没有集成导出功能。而对于“PDF”的导出,一般是先将文件转化为“图片”格式,然后再按照“PDF”格式导出,可以采用“SilverPDF”组件。但是再这两者导出时,不可避免的都会遇到两种问题,第一“DataGrid”导出“Excel”汉字容易乱码,第二“图片”转为“PDF”,图片过大的话,“PDF”以“A4”的大小会显示不全。
下面是自己整理的两种“DataGrid”和“Excel”的导出方法,希望和大家分享。
#region 导出到PDF
/// <summary>
/// 导出到PDF
/// </summary>
public static void ExportToPdf(Chart SLChart)
{
//int chartwidth = SLChart.Width;
//int chartheight = SLChart.Height;
//Chart chartreport = SLChart.Clone();
//SLChart.Margin = new Thickness(100, 100, 100, 100);
SLChart.Width = 600;
SLChart.Height = 250;
//SLChart.Visibility = Visibility.Collapsed;
SaveFileDialog d = new SaveFileDialog();
d.Filter = "PDF file format|*.pdf";
// Save the document...
if (d.ShowDialog() == true)
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
// Create an empty page
PdfPage page = document.AddPage();
//page.Contents.CreateSingleContent().Stream.UnfilteredValue;
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
// Create a font
XFont font = new XFont("Huxtable", 20, XFontStyle.Bold, options);
//WriteableBitmap wb = new WriteableBitmap(SLChart, null);
WriteableBitmap bitmap = new WriteableBitmap(SLChart, null);
MemoryStream stream = Common.GetImageStream(bitmap);
//byte[] b = Convert.FromBase64String(GetBase64Image(wb));
//MemoryStream ms = new MemoryStream(b);
XImage img = XImage.FromStream(stream);
gfx.DrawImage(img, 0, 0, SLChart.ActualWidth, SLChart.ActualHeight);
//PdfDocumentSettings pdfsetting = new PdfDocumentSettings();
//PdfReal pr = new PdfReal();
document.Save(d.OpenFile());
stream.Close();
stream.Dispose();
////SLChart.Margin = new Thickness(0, 0, 0, 0);
//SLChart.Visibility = Visibility.Visible;
}
SLChart.Width = double.NaN;
SLChart.Height = double.NaN;
}
#endregion
#region 导出DataGrid数据到Excel
/// <summary>
/// CSV格式化
/// </summary>
/// <param name="data">数据</param>
/// <returns>格式化数据</returns>
private static string FormatCsvField(string data)
{
return String.Format("\"{0}\"", data.Replace("\"", "\"\"\"").Replace("\n", "").Replace("\r", ""));
}
/// <summary>
/// 导出DataGrid数据到Excel
/// </summary>
/// <param name="withHeaders">是否需要表头</param>
/// <param name="grid">DataGrid</param>
/// <returns>Excel内容字符串</returns>
public static string ExportDataGrid(bool withHeaders, DataGrid grid)
{
System.Reflection.PropertyInfo propInfo;
System.Windows.Data.Binding binding;
var strBuilder = new System.Text.StringBuilder();
var source = (grid.ItemsSource as System.Collections.IList);
if (source == null) return "";
var headers = new List<string>();
grid.Columns.ToList().ForEach(col =>
{
if (col is DataGridBoundColumn)
{ headers.Add(FormatCsvField(col.Header.ToString())); }
});
strBuilder.Append(String.Join(",", headers.ToArray())).Append("\r\n");
foreach (Object data in source)
{
var csvRow = new List<string>();
foreach (DataGridColumn col in grid.Columns)
{
if (col is DataGridBoundColumn)
{
binding = (col as DataGridBoundColumn).Binding;
string colPath = binding.Path.Path;
propInfo = data.GetType().GetProperty(colPath);
if (propInfo != null)
{
csvRow.Add(FormatCsvField("," + propInfo.GetValue(data, null).ToString()));
}
}
}
strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\r\n");
}
return strBuilder.ToString();
}
/// <summary>
/// 导出DataGrid数据到Excel
/// </summary>
/// <param name="withHeaders">是否需要表头</param>
/// <param name="grid">DataGrid</param>
/// <param name="dataBind"></param>
/// <returns>Excel内容字符串</returns>
public static string ExportDataGrid(bool withHeaders, DataGrid grid, bool dataBind)
{
var strBuilder = new System.Text.StringBuilder();
var source = (grid.ItemsSource as System.Collections.IList);
if (source == null) return "";
var headers = new List<string>();
grid.Columns.ToList().ForEach(col =>
{
if (col is DataGridTemplateColumn)
{
headers.Add(col.Header != null ? FormatCsvField(col.Header.ToString()) : string.Empty);
}
});
strBuilder.Append(String.Join(",", headers.ToArray())).Append("\r\n");
foreach (Object data in source)
{
var csvRow = new List<string>();
foreach (DataGridColumn col in grid.Columns)
{
if (col is DataGridTemplateColumn)
{
FrameworkElement cellContent = col.GetCellContent(data);
TextBlock block;
if (cellContent.GetType() == typeof(Grid))
{
block = cellContent.FindName("TempTextblock") as TextBlock;
}
else
{
block = cellContent as TextBlock;
}
if (block != null)
{
csvRow.Add(FormatCsvField(block.Text));
}
}
}
strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\r\n");
//strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\t");
}
return strBuilder.ToString();
}
/// <summary>
/// 导出DataGrid数据到Excel为CVS文件
/// 使用utf8编码 中文是乱码 改用Unicode编码
///
/// </summary>
/// <param name="withHeaders">是否带列头</param>
/// <param name="grid">DataGrid</param>
public static void ExportDataGridSaveAs(bool withHeaders, DataGrid grid)
{
string data = ExportDataGrid(true, grid);
var sfd = new SaveFileDialog
{
DefaultExt = "csv",
Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*",
FilterIndex = 1
};
if (sfd.ShowDialog() == true)
{
using (Stream stream = sfd.OpenFile())
{
using (var writer = new StreamWriter(stream, System.Text.Encoding.Unicode))
{
data = data.Replace(",", "\t");
writer.Write(data);
writer.Close();
}
stream.Close();
}
}
}
/// 导出到PDF
/// </summary>
public static void ExportToPdf(Chart SLChart)
{
//int chartwidth = SLChart.Width;
//int chartheight = SLChart.Height;
//Chart chartreport = SLChart.Clone();
//SLChart.Margin = new Thickness(100, 100, 100, 100);
SLChart.Width = 600;
SLChart.Height = 250;
//SLChart.Visibility = Visibility.Collapsed;
SaveFileDialog d = new SaveFileDialog();
d.Filter = "PDF file format|*.pdf";
// Save the document...
if (d.ShowDialog() == true)
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
// Create an empty page
PdfPage page = document.AddPage();
//page.Contents.CreateSingleContent().Stream.UnfilteredValue;
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
// Create a font
XFont font = new XFont("Huxtable", 20, XFontStyle.Bold, options);
//WriteableBitmap wb = new WriteableBitmap(SLChart, null);
WriteableBitmap bitmap = new WriteableBitmap(SLChart, null);
MemoryStream stream = Common.GetImageStream(bitmap);
//byte[] b = Convert.FromBase64String(GetBase64Image(wb));
//MemoryStream ms = new MemoryStream(b);
XImage img = XImage.FromStream(stream);
gfx.DrawImage(img, 0, 0, SLChart.ActualWidth, SLChart.ActualHeight);
//PdfDocumentSettings pdfsetting = new PdfDocumentSettings();
//PdfReal pr = new PdfReal();
document.Save(d.OpenFile());
stream.Close();
stream.Dispose();
////SLChart.Margin = new Thickness(0, 0, 0, 0);
//SLChart.Visibility = Visibility.Visible;
}
SLChart.Width = double.NaN;
SLChart.Height = double.NaN;
}
#endregion
#region 导出DataGrid数据到Excel
/// <summary>
/// CSV格式化
/// </summary>
/// <param name="data">数据</param>
/// <returns>格式化数据</returns>
private static string FormatCsvField(string data)
{
return String.Format("\"{0}\"", data.Replace("\"", "\"\"\"").Replace("\n", "").Replace("\r", ""));
}
/// <summary>
/// 导出DataGrid数据到Excel
/// </summary>
/// <param name="withHeaders">是否需要表头</param>
/// <param name="grid">DataGrid</param>
/// <returns>Excel内容字符串</returns>
public static string ExportDataGrid(bool withHeaders, DataGrid grid)
{
System.Reflection.PropertyInfo propInfo;
System.Windows.Data.Binding binding;
var strBuilder = new System.Text.StringBuilder();
var source = (grid.ItemsSource as System.Collections.IList);
if (source == null) return "";
var headers = new List<string>();
grid.Columns.ToList().ForEach(col =>
{
if (col is DataGridBoundColumn)
{ headers.Add(FormatCsvField(col.Header.ToString())); }
});
strBuilder.Append(String.Join(",", headers.ToArray())).Append("\r\n");
foreach (Object data in source)
{
var csvRow = new List<string>();
foreach (DataGridColumn col in grid.Columns)
{
if (col is DataGridBoundColumn)
{
binding = (col as DataGridBoundColumn).Binding;
string colPath = binding.Path.Path;
propInfo = data.GetType().GetProperty(colPath);
if (propInfo != null)
{
csvRow.Add(FormatCsvField("," + propInfo.GetValue(data, null).ToString()));
}
}
}
strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\r\n");
}
return strBuilder.ToString();
}
/// <summary>
/// 导出DataGrid数据到Excel
/// </summary>
/// <param name="withHeaders">是否需要表头</param>
/// <param name="grid">DataGrid</param>
/// <param name="dataBind"></param>
/// <returns>Excel内容字符串</returns>
public static string ExportDataGrid(bool withHeaders, DataGrid grid, bool dataBind)
{
var strBuilder = new System.Text.StringBuilder();
var source = (grid.ItemsSource as System.Collections.IList);
if (source == null) return "";
var headers = new List<string>();
grid.Columns.ToList().ForEach(col =>
{
if (col is DataGridTemplateColumn)
{
headers.Add(col.Header != null ? FormatCsvField(col.Header.ToString()) : string.Empty);
}
});
strBuilder.Append(String.Join(",", headers.ToArray())).Append("\r\n");
foreach (Object data in source)
{
var csvRow = new List<string>();
foreach (DataGridColumn col in grid.Columns)
{
if (col is DataGridTemplateColumn)
{
FrameworkElement cellContent = col.GetCellContent(data);
TextBlock block;
if (cellContent.GetType() == typeof(Grid))
{
block = cellContent.FindName("TempTextblock") as TextBlock;
}
else
{
block = cellContent as TextBlock;
}
if (block != null)
{
csvRow.Add(FormatCsvField(block.Text));
}
}
}
strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\r\n");
//strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\t");
}
return strBuilder.ToString();
}
/// <summary>
/// 导出DataGrid数据到Excel为CVS文件
/// 使用utf8编码 中文是乱码 改用Unicode编码
///
/// </summary>
/// <param name="withHeaders">是否带列头</param>
/// <param name="grid">DataGrid</param>
public static void ExportDataGridSaveAs(bool withHeaders, DataGrid grid)
{
string data = ExportDataGrid(true, grid);
var sfd = new SaveFileDialog
{
DefaultExt = "csv",
Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*",
FilterIndex = 1
};
if (sfd.ShowDialog() == true)
{
using (Stream stream = sfd.OpenFile())
{
using (var writer = new StreamWriter(stream, System.Text.Encoding.Unicode))
{
data = data.Replace(",", "\t");
writer.Write(data);
writer.Close();
}
stream.Close();
}
}
}
#endregion 导出DataGrid数据到Excel