1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace Excel.Business
{
/// <summary>
/// Class that handle Export to XML that are compliant with Excel 2007 or higher.
/// </summary>
public static class ExcelXml
{
/// <summary>
/// Export the given DataGrid to Excel XML.
/// </summary>
/// <param name="myGrid">Datagrid to export.</param>
public static void ExportToExcelXml(DataGrid myGrid)
{
if (myGrid.ItemsSource == null)
{
MessageBox.Show("No Data to export!");
return;
}
SaveFileDialog objSFD = new SaveFileDialog() { DefaultExt = "xml", Filter = "Excel XML (*.xml)|*.xml|CSV Files (*.csv)|*.csv|All files (*.*)|*.*", FilterIndex = 1 };
if (objSFD.ShowDialog() == true)
{
MessageBoxResult res = MessageBox.Show("Full export ?", "Export type", MessageBoxButton.OKCancel);
if (res == MessageBoxResult.OK)
{
ExportFullSource(objSFD, myGrid);
}
else
{
ExportDataGrid(objSFD, myGrid);
}
}
}
/// <summary>
/// Export the entire source of the datagrid to Excel.
/// </summary>
/// <param name="objSFD">Object that contains the name of the file that will have datas.</param>
/// <param name="myGrid">Datagrid to export.</param>
private static void ExportFullSource(SaveFileDialog objSFD, DataGrid myGrid)
{
bool firstRow = true;
LinkedList<string> columns = new LinkedList<string>();
string strFormat = objSFD.SafeFileName.Substring(objSFD.SafeFileName.IndexOf('.') + 1).ToUpper();
StringBuilder strBuilder = new StringBuilder();
List<string> lstFields = new List<string>();
try
{
foreach (object data in myGrid.ItemsSource)
{
Type objectType = data.GetType();
if (firstRow)
{
foreach (PropertyInfo item in objectType.GetProperties())
{
columns.AddLast(item.Name);
lstFields.Add(FormatField(item.Name, strFormat));
}
BuildStringOfRow(strBuilder, lstFields, strFormat);
firstRow = false;
}
lstFields.Clear();
foreach (string itemProp in columns)
{
PropertyInfo f = objectType.GetProperty(itemProp);
if (f.GetValue(data, null) == null)
{
lstFields.Add(FormatField(string.Empty, strFormat));
}
else
{
lstFields.Add(FormatField(f.GetValue(data, null).ToString(), strFormat));
}
}
BuildStringOfRow(strBuilder, lstFields, strFormat);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
WriteExcelXmlFile(objSFD, strFormat, strBuilder);
MessageBox.Show("Export Done!!!");
}
}
/// <summary>
/// Export visible datas to an excel sheet.
/// </summary>
/// <param name="objSFD">Object that contains the name of the file that will have datas.</param>
/// <param name="myGrid">Datagrid to export.</param>
private static void ExportDataGrid(SaveFileDialog objSFD, DataGrid myGrid)
{
string strFormat = objSFD.SafeFileName.Substring(objSFD.SafeFileName.IndexOf('.') + 1).ToUpper();
StringBuilder strBuilder = new StringBuilder();
List<string> lstFields = new List<string>();
if (myGrid.HeadersVisibility == DataGridHeadersVisibility.Column || myGrid.HeadersVisibility == DataGridHeadersVisibility.All)
{
foreach (DataGridColumn dgcol in myGrid.Columns)
{
lstFields.Add(FormatField(dgcol.Header.ToString(), strFormat));
}
BuildStringOfRow(strBuilder, lstFields, strFormat);
}
try
{
foreach (object data in myGrid.ItemsSource)
{
lstFields.Clear();
foreach (DataGridColumn col in myGrid.Columns)
{
string strValue = string.Empty;
Binding objBinding = null;
if (col is DataGridBoundColumn)
{
objBinding = (col as DataGridBoundColumn).Binding;
}
if (col is DataGridTemplateColumn)
{
// This is a template column... let us see the underlying dependency object
try
{
DependencyObject objDO = (col as DataGridTemplateColumn).CellTemplate.LoadContent();
FrameworkElement oFE = (FrameworkElement)objDO;
FieldInfo oFI = oFE.GetType().GetField("TextProperty");
if (oFI != null)
{
if (oFI.GetValue(null) != null)
{
if (oFE.GetBindingExpression((DependencyProperty)oFI.GetValue(null)) != null)
{
objBinding = oFE.GetBindingExpression((DependencyProperty)oFI.GetValue(null)).ParentBinding;
}
}
}
}
catch
{
objBinding = null;
}
}
if (objBinding != null)
{
if (objBinding.Path.Path != string.Empty)
{
PropertyInfo pi = data.GetType().GetProperty(objBinding.Path.Path);
if (pi != null)
{
strValue = pi.GetValue(data, null).ToString();
}
}
if (objBinding.Converter != null)
{
if (strValue != string.Empty)
{
strValue = objBinding.Converter.Convert(strValue, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString();
}
else
{
strValue = objBinding.Converter.Convert(data, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString();
}
}
}
lstFields.Add(FormatField(strValue, strFormat));
}
BuildStringOfRow(strBuilder, lstFields, strFormat);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
WriteExcelXmlFile(objSFD, strFormat, strBuilder);
MessageBox.Show("Export Done!!!");
}
/// <summary>
/// Write to Excel XML file.
/// </summary>
/// <param name="objSFD">Object that contains destination filename.</param>
/// <param name="strFormat">XML to indicate the destination is a XML file, otherwise it is a CSV file.</param>
/// <param name="strBuilder">Datas well formatted.</param>
private static void WriteExcelXmlFile(SaveFileDialog objSFD, string strFormat, StringBuilder strBuilder)
{
StreamWriter sw = new StreamWriter(objSFD.OpenFile());
if (strFormat == "XML")
{
// Let us write the headers for the Excel XML
sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sw.WriteLine("<?mso-application progid=\"Excel.Sheet\"?>");
sw.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\">");
sw.WriteLine("<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">");
sw.WriteLine("<Author>" + App.Current.Host.InitParams["UserName"].ToString() + "</Author>");
sw.WriteLine("<Created>" + DateTime.Now.ToLocalTime().ToLongDateString() + "</Created>");
sw.WriteLine("<LastSaved>" + DateTime.Now.ToLocalTime().ToLongDateString() + "</LastSaved>");
sw.WriteLine("<Company>My Company</Company>");
sw.WriteLine("<Version>12.00</Version>");
sw.WriteLine("</DocumentProperties>");
sw.WriteLine("<Worksheet ss:Name=\"Excel Export\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">");
sw.WriteLine("<Table>");
}
sw.Write(strBuilder.ToString());
if (strFormat == "XML")
{
sw.WriteLine("</Table>");
sw.WriteLine("</Worksheet>");
sw.WriteLine("</Workbook>");
}
sw.Close();
}
/// <summary>
/// Build the destination string.
/// </summary>
/// <param name="strBuilder">Destination buffer.</param>
/// <param name="lstFields">Collection of string that contains row datas.</param>
/// <param name="strFormat">Format of the destination file. Xml or Csv.</param>
private static void BuildStringOfRow(StringBuilder strBuilder, List<string> lstFields, string strFormat)
{
switch (strFormat)
{
case "XML":
strBuilder.AppendLine("<Row>");
strBuilder.AppendLine(String.Join("\r\n", lstFields.ToArray()));
strBuilder.AppendLine("</Row>");
break;
case "CSV":
strBuilder.AppendLine(String.Join(",", lstFields.ToArray()));
break;
}
}
/// <summary>
/// Format field regarding destination file format.
/// </summary>
/// <param name="data">Data to fomat.</param>
/// <param name="format">Format of the destination file. Xml or CSV.</param>
/// <returns>Formatted field.</returns>
private static string FormatField(string data, string format)
{
switch (format)
{
case "XML":
return String.Format("<Cell><Data ss:Type=\"String\">{0}</Data></Cell>", data);
case "CSV":
return String.Format("\"{0}\"", data.Replace("\"", "\"\"\"").Replace("\n", string.Empty).Replace("\r", string.Empty));
}
return data;
}
}
} |
Partager