Created
May 8, 2020 01:50
-
-
Save MERZAK-X/53b7b9eb1ed77e18030e1c9e62c10714 to your computer and use it in GitHub Desktop.
Export DataGridView to CSV (filename = file path)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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