Thursday, January 6, 2011

Export to Excel using StreamWriter

I assume that you had filled a datagriview with a datatable and add namespace System.IO

// Set location to save the file, name and extension
SaveFileDialog SaveFile = new SaveFileDialog();
SaveFile.DefaultExt = "csv";
SaveFile.FileName = "HojaTest";
SaveFile.Filter = "csv";
 
if (SaveFile.ShowDialog() == DialogResult.OK)
{
SaveFile.AddExtension = true;
//Create File
StreamWriter sw = new StreamWriter(SaveFile.FileName, false);
string Headers = "";
 
//Write headers to the file
foreach (DataGridViewColumn col in grid.Columns)
{
    if (Headers != "")
         Headers += ",";
    Headers += col.Name;
}
sw.Write(Headers);
sw.Write(sw.NewLine); 
 
//Write the informacion to excel file
foreach (DataRow row in table.Rows)
{
     for (int i = 0; i < table.Columns.Count ; i++)
     {
           if (!row[i].Equals(DBNull.Value))
                sw.Write(row[i].ToString().Replace(",", "."));
           if (i < table.Columns.Count - 1)
                 sw.Write(",");
      }
sw.Write(sw.NewLine);
}
sw.Close();
MessageBox.Show("Datos Exportados");

No comments:

Post a Comment