Silverlight Export DataGrid Data

    /// <summary>
    /// Export helper.
    /// </summary>
    public class ExportHelper
    {
        /// <summary>
        /// Export all data.
        /// </summary>
        /// <typeparam name="T">Data Source Type.</typeparam>
        /// <param name="dataGrid">Data Grid.</param>
        /// <param name="dataSource">Data Source.</param>
        public static void ExportAllData<T>(DataGrid dataGrid, IEnumerable<T> dataSource)
        {
            if (dataGrid.ItemsSource == null || dataSource == null)
            {
                return;
            }

            SaveFileDialog dialog2 = new SaveFileDialog();
            dialog2.DefaultExt = "xls";
            dialog2.Filter = "Excel (*.xls)|*.xls";
            dialog2.FilterIndex = 1;
            SaveFileDialog dialog = dialog2;
            if (dialog.ShowDialog() == true)
            {
                bool needExport;
                string format = dialog.SafeFileName.Substring(dialog.SafeFileName.LastIndexOf('.') + 1).ToUpper();
                StringBuilder strBuilder = new StringBuilder();
                List<string> lstFields = new List<string>();
                List<double> colsWidth = new List<double>();
                if ((dataGrid.HeadersVisibility == DataGridHeadersVisibility.Column) || (dataGrid.HeadersVisibility == DataGridHeadersVisibility.All))
                {
                    foreach (DataGridColumn column in dataGrid.Columns)
                    {
                        needExport = true;
                        if (column is OVS.DataGridTextColumn)
                        {
                            needExport = (column as OVS.DataGridTextColumn).NeedExport;
                        }
                        else if (column is DataGridTemplateColumn)
                        {
                            needExport = (column as OVS.DataGridTemplateColumn).NeedExport;
                        }

                        if (needExport)
                        {
                            if (column.Header == null)
                            {
                                lstFields.Add(FormatField(string.Empty, format));
                            }
                            else
                            {
                                lstFields.Add(FormatField(column.Header.ToString(), format));
                            }

                            colsWidth.Add(column.ActualWidth);
                        }
                    }

                    FormatCellWidth(strBuilder, colsWidth, format);
                    BuildStringOfRow(strBuilder, lstFields, format);
                }

                foreach (object obj2 in dataSource)
                {
                    lstFields.Clear();
                    foreach (DataGridColumn column2 in dataGrid.Columns)
                    {
                        needExport = true;
                        if (column2 is DataGridTextColumn)
                        {
                            needExport = (column2 as OVS.DataGridTextColumn).NeedExport;
                        }
                        else if (column2 is DataGridTemplateColumn)
                        {
                            needExport = (column2 as OVS.DataGridTemplateColumn).NeedExport;
                        }

                        if (needExport)
                        {
                            object objValue = null;
                            Binding binding = null;
                            string field = null;

                            if (column2 is DataGridBoundColumn)
                            {
                                binding = (column2 as DataGridBoundColumn).Binding;
                            }

                            if (column2 is DataGridTemplateColumn)
                            {
                                OVS.DataGridTemplateColumn column3 = column2 as OVS.DataGridTemplateColumn;

                                if (!((column3 == null) || string.IsNullOrWhiteSpace(column3.ExportField)))
                                {
                                    field = column3.ExportField;
                                }
                            }

                            if (field != null)
                            {
                                GetPropertyValueByField(obj2, ref objValue, field);
                            }

                            if (binding != null)
                            {
                                if (binding.Path.Path != string.Empty)
                                {
                                    string str3 = binding.Path.Path;
                                    GetPropertyValueByField(obj2, ref objValue, str3);
                                }

                                if ((binding.Converter != null) && (objValue != null))
                                {
                                    objValue = binding.Converter.Convert(objValue, typeof(string), binding.ConverterParameter, binding.ConverterCulture).ToString();
                                }
                            }

                            lstFields.Add(FormatField((objValue != null) ? objValue.ToString() : string.Empty, format));
                        }
                    }

                    BuildStringOfRow(strBuilder, lstFields, format);
                }

                Stream stream = null;

                try
                {
                    stream = dialog.OpenFile();
                }
                catch
                {
                    MessageBox.Show("Export exception!");
                    return;
                }

                if (stream != null)
                {
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        if (format == "XLS")
                        {
                            writer.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                            writer.WriteLine("<?mso-application progid=\"Excel.Sheet\"?>");
                            writer.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\">");
                            writer.WriteLine("<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">");
                            writer.WriteLine("<Author>Arasu Elango</Author>");
                            writer.WriteLine("<Created>" + DateTime.Now.ToLocalTime().ToLongDateString() + "</Created>");
                            writer.WriteLine("<LastSaved>" + DateTime.Now.ToLocalTime().ToLongDateString() + "</LastSaved>");
                            writer.WriteLine("<Company>Atom8 IT Solutions (P) Ltd.,</Company>");
                            writer.WriteLine("<Version>12.00</Version>");
                            writer.WriteLine("</DocumentProperties>");
                            writer.WriteLine("<Worksheet ss:Name=\"Export Data\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">");
                            writer.WriteLine("<Table>");
                        }

                        writer.Write(strBuilder.ToString());

                        if (format == "XLS")
                        {
                            writer.WriteLine("</Table>");
                            writer.WriteLine("</Worksheet>");
                            writer.WriteLine("</Workbook>");
                        }

                        writer.Close();
                    }
                }
            }
        }

        #region Private method

        /// <summary>
        /// Build string of row.
        /// </summary>
        /// <param name="strBuilder">String builder.</param>
        /// <param name="lstFields">Last Fields.</param>
        /// <param name="strFormat">String format.</param>
        private static void BuildStringOfRow(StringBuilder strBuilder, List<string> lstFields, string strFormat)
        {
            string str = strFormat;

            if (str != null)
            {
                if (!(str == "XLS"))
                {
                    if (str == "CSV")
                    {
                        strBuilder.AppendLine(string.Join(",", lstFields.ToArray()));
                    }
                }
                else
                {
                    strBuilder.AppendLine("<Row>");
                    strBuilder.AppendLine(string.Join("\r\n", lstFields.ToArray()));
                    strBuilder.AppendLine("</Row>");
                }
            }
        }

        /// <summary>
        /// Format cell width.
        /// </summary>
        /// <param name="strBuilder">String builder.</param>
        /// <param name="colsWidth">Column width.</param>
        /// <param name="strFormat">String Format.</param>
        private static void FormatCellWidth(StringBuilder strBuilder, List<double> colsWidth, string strFormat)
        {
            int index = 1;

            colsWidth.ForEach(delegate(double p)
            {
                string text1 = strFormat;

                if ((text1 != null) && (text1 == "XLS"))
                {
                    strBuilder.AppendLine(string.Format("<Column ss:Index='{0}' ss:AutoFitWidth='0' ss:Width='{1}'/>", index, colsWidth[index - 1]));
                }

                index++;
            });
        }

        /// <summary>
        /// Format field.
        /// </summary>
        /// <param name="data">String Data.</param>
        /// <param name="format">String format.</param>
        /// <returns>Return format field.</returns>
        private static string FormatField(string data, string format)
        {
            data = data.Replace("<", "\t<").Replace(">", ">");
            string str2 = format;

            if (str2 == null)
            {
                return data;
            }

            if (!(str2 == "XLS"))
            {
                if (str2 == "CSV")
                {
                    return string.Format("\"{0}\"", data.Replace("\"", "\"\"\"").Replace("\n", string.Empty).Replace("\r", string.Empty));
                }

                return data;
            }

            return string.Format("<Cell><Data ss:Type=\"String\">{0}</Data></Cell>", data);
        }

        /// <summary>
        /// Get property value by field.
        /// </summary>
        /// <param name="data">Field data.</param>
        /// <param name="objValue">Object value.</param>
        /// <param name="field">Field reulst.</param>
        private static void GetPropertyValueByField(object data, ref object objValue, string field)
        {
            List<string> properties = Enumerable.ToList<string>(field.Split(new char[] { '.' }));

            if (properties.Count == 1)
            {
                PropertyInfo property = data.GetType().GetProperty(field);
                if (property != null)
                {
                    object obj2 = property.GetValue(data, null);
                    objValue = obj2;
                }
            }
            else if (properties.Count > 1)
            {
                GetValue(data, ref objValue, properties);
            }
        }

        /// <summary>
        /// Get value.
        /// </summary>
        /// <param name="data">Field data.</param>
        /// <param name="objValue">Object value.</param>
        /// <param name="properties">Properties value.</param>
        private static void GetValue(object data, ref object objValue, List<string> properties)
        {
            Queue<string> queue = new Queue<string>();

            foreach (string str in properties)
            {
                queue.Enqueue(str);
            }

            object propertyValue = GetPropertyValue(data, queue);

            if (propertyValue != null)
            {
                objValue = propertyValue;
            }
        }

        /// <summary>
        /// Get property value.
        /// </summary>
        /// <param name="data">Field data.</param>
        /// <param name="queue">Queue string.</param>
        /// <returns>Return property value.</returns>
        private static object GetPropertyValue(object data, Queue<string> queue)
        {
            string name = queue.Dequeue();
            PropertyInfo property = data.GetType().GetProperty(name);

            if (property != null)
            {
                object obj2 = property.GetValue(data, null);
                if (queue.Count > 0)
                {
                    return GetPropertyValue(obj2, queue);
                }

                return obj2;
            }

            return null;
        }

        #endregion
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章