Option 1
To export a DataGridView
to file, as a simple option you can use GetClipboardContent
methos:
grid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
grid.SelectAll();
var text = grid.GetClipboardContent().GetText();
Then you can simply use File.WriteAllText
method to save contents to file:
System.IO.File.WriteAllText(filePath, text);
Note
- You can select only columns or rows which you want to export. I used
SelectAll()
to export the whole grid.
- You can have more control on exported text using this signature of
GetText
method.
Option 2
You can use linq to select cell values which you want and join them to create the text representation of DataGridView
:
var lines = new List<string>();
var headers = grid.Columns.Cast<DataGridViewColumn>()
.Where(c => c.Visible).Select(c => c.HeaderText);
lines.Add(string.Join("\t", headers));
var rows = grid.Rows.Cast<DataGridViewRow>()
.Select(r => string.Join("\t", r.Cells.Cast<DataGridViewCell>()
.Where(c => c.Visible).Select(c => c.FormattedValue)));
lines.AddRange(rows);
var text = string.Join(Environment.NewLine, lines);