Skip to content

Instantly share code, notes, and snippets.

@MERZAK-X
Created May 8, 2020 01:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MERZAK-X/53b7b9eb1ed77e18030e1c9e62c10714 to your computer and use it in GitHub Desktop.
Save MERZAK-X/53b7b9eb1ed77e18030e1c9e62c10714 to your computer and use it in GitHub Desktop.
Export DataGridView to CSV (filename = file path)
public static bool export2CSV(DataGridView dgv, string filename)
{
bool pass = false;
/*// Method 1
dgv.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText; // Choose whether to write header. Use EnableWithoutHeaderText instead to omit header.
dgv.SelectAll(); // Select all the cell
DataObject dataObject = dgv.GetClipboardContent(); // Copy selected cells to DataObject
if (dataObject != null)
{
// Get the text of the DataObject, and serialize it to a file
File.WriteAllText(filename, dataObject.GetText(TextDataFormat.CommaSeparatedValue));
pass = true;
}*/
// Method 2
var sb = new StringBuilder();
var headers = dgv.Columns.Cast<DataGridViewColumn>();
sb.AppendLine(string.Join(",", headers.Select(column => "\"" + column.HeaderText + "\"").ToArray()));
foreach (DataGridViewRow row in dgv.Rows)
{
var cells = row.Cells.Cast<DataGridViewCell>();
sb.AppendLine(string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
}
System.IO.File.WriteAllText(filename, sb.ToString());
pass = true;
return pass;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment