使用下面的代码,我使用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());
}
答案 0 :(得分:1)
要在按钮上单击以在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);
}
答案 1 :(得分:0)
您有两种方法,可以使用DataTable:
How to export DataTable to Excel
或者您可以使用DataGridView" DG1":
https://code.msdn.microsoft.com/office/How-to-Export-DataGridView-62f1f8ff