I have a question, how do I press the button to transfer the contents of the grid to the clipboard .... or to Excel? if you can please write the code Thank you)))) (C # (/ WPF))
1 answer
coupled with all the questions and suggestions, I can only offer this, because I am not so familiar with the issues of performance and other things:
StringBuilder builder = new StringBuilder(""); for (int i = 0; i < grid.Rows.Count; i++) { for (int j = 0; j < grid.Columns.Count; j++) { builder.Append(grid[j, i].Value.ToString()); builder.Append(";"); } builder.Replace(";", "|", builder.Length - 1, 1); } builder.Remove(builder.Length - 1, 1); string data = builder.ToString(); data = data.Replace("|", "\n"); Clipboard.SetText(data, TextDataFormat.CommaSeparatedValue);
Here I used the CSV standard for Russian Excel, where the values are separated by the symbol ";", and the lines are simply the symbol of the transition to the next line. If you wish, you can run the following code, which saves for you a CSV file, freely digested by Excel:
File.WriteAllText(@"D:\file.csv", data, Encoding.Default);
When using the DataTable from the System.Data namespace, you need to replace the grid [j, i] .Value.ToString () with, for example, table.Rows [i] [j] .ToString ()
- And another question .... And if you use a table .... how to copy from it? I tried to apply this code to the table .... ie. How can I refer to rows, columns [j, i] of a table? - Rakzin Roman
- I would not use the operator '+ =' in the loop, since each time a new line is created, which can affect performance. It’s better to use StringBulder.Append (). - Mihey
- Thanks, it works)))))))) If you need someone, add the project using System.Text first; and using System.IO ;, if you create a file. - Rakzin Roman
|