C#中DataGrid匯出Excel檔案

無海發表於2024-03-25
        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            grid.SelectAllCells();
            grid.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
            ApplicationCommands.Copy.Execute(null, grid);
            string result = (string)Clipboard.GetData(DataFormats.Text);
            SaveFileDialog sfd = new SaveFileDialog();
            string dtNow = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            sfd.FileName = dtNow + "匯出到Excel";
            sfd.Filter = "Excel檔案(*.xls)|*.xls|Csc檔案(*.csv)|*.csv|所有檔案(*.*)|*.*";
            if (sfd.ShowDialog() == true)
            {
                string path = System.IO.Path.GetDirectoryName(sfd.FileName);
                grid.UnselectAllCells();
                StreamWriter swr = new StreamWriter(sfd.FileName);
                swr.WriteLine(result.Replace(',', ' '));
                swr.Close();
                sw.Stop();
                string timeSpan = sw.ElapsedMilliseconds.ToString();
                long num = grid.Items.Count;
                MessageBox.Show("共有" + num + "條資料!\n" + "匯出到" + path + "!\n" + "共耗時" + timeSpan + "毫秒!\n");
            }
        }

相關文章