Copy text from WPF DataGrid to Clipboard to Excel

11,556

Solution 1

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

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

Solution 2

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

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

should work.

Share:
11,556
KMC
Author by

KMC

Tutorials: WPF C# Databinding C# Programming Guide .NET Framework Data Provider for SQL Server Entity Framework LINQ-to-Entity The Layout System Resources: LifeCharts: free .NET charts FileHelper: text file helper cmdow

Updated on June 09, 2022

Comments

  • KMC
    KMC almost 2 years

    I have WPF DataGrid (VS2010 C#). I copied the data from DataGrid to Clipboard and write 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 out OK except when I open the excel file it gives me two warning:

    "The file you are trying to open 'test.xls' is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?"

    "Excel has detected that 'test.xls' is a SYLK file, but cannot load it."

    But after I click through it, it still open the excel file OK and data are formated as it supposed to be. But I can't find how to get rid of the two warnings before the excel file is open.

    • Jaime Oro
      Jaime Oro about 13 years
      I think It's becouse the file hasn't got the correct extension.
    • KMC
      KMC about 13 years
      Excel has an extension of ".xls"... isn't it?
    • Brian J
      Brian J almost 11 years
      Excel Spreadsheets are .xls. But Excel can open other file formats as well, such as a comma separated value file (.csv)