天天看點

Silverlight Datagrid 導出 Excel

注意:以下代碼未經本人測試,僅供參考

void btnExport_Click(object sender, RoutedEventArgs e)

        {

            ExportExcel.ExportDataGridSaveAs(true,this.dg);

        }

導出類檔案如下:

  public static class ExportExcel

    {

        #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", ""));

        }

        /// 導出DataGrid資料到Excel

        /// <param name="withHeaders">是否需要表頭</param>

        /// <param name="grid">DataGrid</param>

        /// <returns>Excel内容字元串</returns>

        public static string ExportDataGrid(bool withHeaders, DataGrid grid)

            string colPath; System.Reflection.PropertyInfo propInfo;

            System.Windows.Data.Binding binding;

            System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();

            System.Collections.IList source = (grid.ItemsSource as System.Collections.IList);

            if (source == null) return "";

            List<string> 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)

                List<string> csvRow = new List<string>();

                foreach (DataGridColumn col in grid.Columns)

                {

                    if (col is DataGridBoundColumn)

                    {

                        binding = (col as DataGridBoundColumn).Binding;

                        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();

        public static string ExportDataGrid(bool withHeaders, DataGrid grid, bool dataBind)

            string colPath;

            System.Reflection.PropertyInfo propInfo;

                if (col is DataGridTemplateColumn)

                    if (col.Header != null)

                        headers.Add(FormatCSVField(col.Header.ToString()));

                    else

                        headers.Add(string.Empty);

                    if (col is DataGridTemplateColumn)

                        FrameworkElement cellContent = col.GetCellContent(data);

                        TextBlock block = null;

                        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("\t");

        /// 導出DataGrid資料到Excel為CVS檔案

        /// 使用utf8編碼 中文是亂碼  改用Unicode編碼

        /// 

        /// <param name="withHeaders">是否帶列頭</param>

        public static void ExportDataGridSaveAs(bool withHeaders, DataGrid grid)

            string data =ExportDataGrid(true, grid);

            SaveFileDialog sfd = new SaveFileDialog()

                DefaultExt = "csv",

                Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*",

                FilterIndex = 1

            };

            if (sfd.ShowDialog() == true)

                using (Stream stream = sfd.OpenFile())

                    using (StreamWriter writer = new StreamWriter(stream, System.Text.UnicodeEncoding.Unicode))

                        data = data.Replace(",", "\t");

                        writer.Write(data);

                        writer.Close();

                    stream.Close();

        #endregion 導出DataGrid資料到Excel