wpf 視窗程式下將datagrid匯出為excel

badwell發表於2015-04-09

    今天用了幾個小時也沒有找到將datagrid匯出為excel的方法,搜尋msdn發現,老外也木有解決這個問題,因此把程式碼貼出來,和大家分享一下,提高工作效率。簡要說一哈,本程式使用反射,因此程式碼量看起來,很少,但是執行效率,還在沒有進行優化處理。

   #region  wpf客戶端 匯出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>
        /// <param name="dataBind"></param>
        /// <returns>Excel內容字串</returns>
        public static string ExportDataGrid(bool withHeaders, System.Windows.Controls.DataGrid grid, bool dataBind)
        {
            try
            {
                var strBuilder = new System.Text.StringBuilder();
                var source = (grid.ItemsSource as System.Collections.IList);
                if (source == null) return "";
                var headers = new List<string>();
                List<string> bt = new List<string>();

                foreach (var hr in grid.Columns)
                {
                    //   DataGridTextColumn textcol = hr. as DataGridTextColumn;
                    headers.Add(hr.Header.ToString());
                    if (hr is DataGridTextColumn)//列繫結資料
                    {
                        DataGridTextColumn textcol = hr as DataGridTextColumn;
                        if (textcol != null)
                            bt.Add((textcol.Binding as Binding).Path.Path.ToString());        //獲取繫結源      
                        
                    }else if(hr is DataGridTemplateColumn)
                    {
                        if(hr.Header.Equals("操作"))
                        bt.Add("Id");
                    }
                    else
                    {

                    }
                }
                strBuilder.Append(String.Join(",", headers.ToArray())).Append("\r\n");
                foreach (var data in source)
                {
                    var csvRow = new List<string>();
                   foreach(var ab in bt)
                   {
                       string s = ReflectionUtil.GetProperty(data, ab).ToString();
                       if(s!=null)
                       {
                           csvRow.Add(FormatCsvField(s));
                       }
                       else
                       {
                           csvRow.Add("\t");
                       }
                   }
                    strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\r\n");
                   // strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\t");
                }
                return strBuilder.ToString();
            }catch(Exception ex)
            {
                LogHelper.Error(ex);
                return "";
            }
        }
        /// <summary>
        /// 匯出DataGrid資料到Excel為CVS檔案
        /// 使用utf8編碼 中文是亂碼 改用Unicode編碼
        /// 
        /// </summary>
        /// <param name="withHeaders">是否帶列頭</param>
        /// <param name="grid">DataGrid</param>
        public static void ExportDataGridSaveAs(bool withHeaders, System.Windows.Controls.DataGrid grid)
        {
            try
            {
                string data = ExportDataGrid(true, grid, true);
                var sfd = new Microsoft.Win32.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();
                    }
                }
                MessageBox.Show("匯出成功!");
            }catch(Exception ex)
            {
                LogHelper.Error(ex);
            }
        }

        #endregion 匯出DataGrid資料到Excel
    }

 

相關文章