How to save datatable as a .csv file?
Code is written in C# and application is windows based application.
You can create a class library and put this code snippet in to it and call whenever it is required.
.CSV is a comma seperated file.
Description This method is used to take datatable as a parameter and save all datatable contents as .csv file.
public void ConvertDatatableToCSV(Datatable user_defined_datatable )
{
private System.Windows.Forms.SaveFileDialog user_save_dialog_box;
try
{
user_save_dialog_box.Filter = "CSV Files | *.csv";
if (user_save_dialog_box.ShowDialog() != System.Windows.Forms.DialogResult.Cancel)
{
user_defined_file_name = user_save_dialog_box.FileName;
Microsoft.Office.Interop.Excel.Application excelApplication = new Microsoft.Office.Interop.Excel.Application();
excelApplication.Visible = false;
Microsoft.Office.Interop.Excel.Workbook workbook = excelApplication.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.ActiveSheet;
// This is used for Header.
for (int i = 0; i < user_defined_datatable.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = user_defined_datatable.Columns[i].ColumnName;
}
// This is used for contents
for (int i = 0; i < user_defined_datatable.Rows.Count; i++)
{
for (int j = 0; j < user_defined_datatable.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = user_defined_datatable.Rows[i][j].ToString();
}
}
workbook.SaveAs(user_defined_file_name, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, false, false, Type.Missing, Type.Missing, Type.Missing);
workbook.Close(true, Type.Missing, Type.Missing);
excelApplication.Quit();
}
}
catch
{
MessageBox.Show("Save Error", "Application_name", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
}