Below is the function which is written in C#, which will demonstrates how to save all datagridview record into CSV(Comma separated file).
public void ExportGridToCSV()
{
string filename = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "CSV (*.csv)|*.csv";
sfd.FileName = "Output.csv";
if (sfd.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("Data will be exported and you will be notified when it is ready.");
if (File.Exists(filename))
{
try
{
File.Delete(filename);
}
catch (IOException ex)
{
MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
}
}
int columnCount = dataGridView1.ColumnCount;
string columnNames = "";
string[] output = new string[dataGridView1.RowCount + 1];
for (int i = 0; i < columnCount; i++)
{
columnNames += dataGridView1.Columns[i].Name.ToString() + ",";
}
output[0] += columnNames;
for (int i = 1; (i - 1) < dataGridView1.RowCount; i++)
{
for (int j = 0; j < columnCount; j++)
{
try
{
output[i] += dataGridView1.Rows[i - 1].Cells[j].Value.ToString() + ",";
}
catch (Exception ex)
{
// MessageBox.Show("Error"+ex);
}
}
}
System.IO.File.WriteAllLines(sfd.FileName, output, System.Text.Encoding.UTF8);
MessageBox.Show("Your file was generated and its ready for use.");
}
}
Comments
Post a Comment