Copy text from WPF DataGrid to clipboard in Excel

I have a WPF DataGrid (VS2010 C #). I copied the data from the DataGrid to the clipboard and wrote it to an Excel file. Below is my code.

dataGrid1.SelectAllCells(); dataGrid1.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader; ApplicationCommands.Copy.Execute(null, dataGrid1); dataGrid1.UnselectAllCells(); string path1 = "C:\\test.xls"; string result1 = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue); Clipboard.Clear(); System.IO.StreamWriter file1 = new System.IO.StreamWriter(path1); file1.WriteLine(result1); file1.Close(); 

Everything works fine, except when I open the excel file, it gives me two warnings:

"The file you are trying to open 'test.xls' is in a different format than indicated by the file extension. Make sure the file is not corrupted and open the file from a reliable source. Do you want to open the file now?"

"Excel found that the" test.xls "file is SYLK, but cannot load it."

But after I go through it, it will still open the excel OK file, and the data will be generated as expected. But I can not find how to get rid of two warnings before the Excel file is opened.

+6
clipboard wpf
source share
2 answers

A problem similar to yours has already been described here: generating / opening CSV from the console - the file is in the wrong format error . Does it help you solve your problem?

Edit: Here is the Microsoft related KB => http://support.microsoft.com/kb/323626

+2
source share

You need to use csv as an extension. Xls is an Excel file extension. So

 string path1 = "C:\\test.csv"; 

must work.

+4
source share

All Articles