How can I properly format text to paste it from C# to Excel?

3.3k views Asked by At

I have button in my c# application that should format and copy data from few sources.

And i have a problem to paste my text from clipboard to excel.

In excel all text like 1.12.1 is transfromed to 01.12.2001 datetime format! And i dont want to do like that!

foreach (var data in collection)
{
  sb.Append(data.Column1+ "\t");
  sb.Append(data.Column2+ "\t");
  sb.Append(data.Column33+ "\t");

  sb.AppendLine();
}

var clipboardResults = new DataObject();
clipboardResults.SetData(DataFormats.Text, sb.ToString());
Clipboard.SetDataObject(clipboardResults);

Is it possible to format my text so excel will understand that copied data is text and not date time!

2

There are 2 answers

1
Kevin On BEST ANSWER

Did you try putting the text identifier (single quote) in front of it?

e.g. '1.12.1

0
Maxime Biette On

In the Excel document where you are going to paste the data, you need to select and set the format of the destination cells as Text. It will prevent Excel from trying to interpret the data when you paste it.

To avoid doing that, you can try using the XML Spreadsheet Format: C# Add excel text-formatted data to clipboard