使用 c# 将 wpf 中的数据网格导出到 excel

Export the datagrid in wpf to excel using c#

使用以下代码,我使用 C# 从 MS 访问数据库在 WPF 中加载了 datagrid,但不确定如何将相同的 datagrid 导出到 Excel。

try
{
    OleDbConnection connect = new OleDbConnection();
    connect.ConnectionString = 
    @"Provider=Microsoft.ACE.OLEDB.12.0;DataSource=|DataDirectory|\Electricalcircuits.mdb";

    OleDbCommand cmd = new OleDbCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "Select * from REPORT";
    cmd.Connection = connect;
    connect.Open();
    System.Data.DataTable dt = new System.Data.DataTable();
    OleDbDataAdapter DA = new OleDbDataAdapter(cmd);
    DA.Fill(dt);
    DG1.ItemsSource = dt.AsDataView();

}
catch (OleDbException ex)
{
    MessageBox.Show(ex.ToString());
}

你有两种方法,你可以使用DataTable:

How to export DataTable to Excel

或者您可以使用 DataGridView "DG1":

https://code.msdn.microsoft.com/office/How-to-Export-DataGridView-62f1f8ff

在 WPF 中使用 C# 在单击按钮时将 DataGrid 导出到 Excel(Csv)

private void btnExport_Click(object sender, RoutedEventArgs e)
  {            
     string ExportName = (sender as System.Windows.Controls.Button).Name.ToString();
     bool result = Export.SaveToCSV(TrkDataGrid, ExportName);//pass the Datagrid and Exportname
     if (result == true)
     {
      MessageBoxResult result = System.Windows.MessageBox.Show("Exported successfully", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
     }
  }
 public bool SaveToCSV(System.Windows.Controls.DataGrid dataGrid,string Filename)
  {
    bool IsVaild = false;
    SaveFileDialog saveFileDialog = new SaveFileDialog();
    saveFileDialog.Title = "Save CSV Files";
    saveFileDialog.Filter = "CSV file (*.csv)|*.csv";
    saveFileDialog.FileName = Filename;           
    string gridname = Filename;
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
     string  path = System.IO.Path.GetFullPath(saveFileDialog.FileName);                    
     createcsvfile(dataGrid, path);              
      IsVaild = true;
    }
    return IsVaild;      
  }
 private void createcsvfile(System.Windows.Controls.DataGrid dataGrid, string FilePath)
  {            
    dataGrid.SelectAllCells();
    dataGrid.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;           
    ApplicationCommands.Copy.Execute(null, dataGrid);
    dataGrid.UnselectAllCells();
    String result = (string)System.Windows.Clipboard.GetData(System.Windows.DataFormats.CommaSeparatedValue);
    File.AppendAllText(FilePath, result, UnicodeEncoding.UTF8);         
  }