0

i want to export data from multiple datatables to csv file.

i already know how to write one datatable to csv.

any help please. i have this function

 public void CreateCSVFile(DataTable dt, string strFilePath)  
 {  
   try  
   {  
     StreamWriter sw = new StreamWriter(strFilePath, false);  
     int columnCount = dt.Columns.Count;  
     for (int i = 0; i < columnCount ; i++)  
     {  
       sw.Write(dt.Columns[i]);  
       if (i < columnCount - 1)  
       {  
         sw.Write(",");  
       }  
     }  
     sw.Write(sw.NewLine);  
     foreach (DataRow dr in dt.Rows)  
     {  
       for (int i = 0; i < columnCount ; i++)  
       {  
         if (!Convert.IsDBNull(dr[i]))  
         {  
           sw.Write(dr[i].ToString());  
         }  
         if (i < columnCount - 1)  
         {  
           sw.Write(",");  
         }  
       }  
       sw.Write(sw.NewLine);  
     }  
     sw.Close();  
   }  
   catch (Exception ex)  
   {  
     throw ex;  
   }  
 }  
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
user3258052
  • 59
  • 1
  • 2
  • 7

2 Answers2

1

only pass the data table to the function and name of report it will output a report file.

     public void MyGetCSV(DataTable dtRecords,string strReportName)
    {
        string delimiter = ",";
        StringBuilder csvGen = new StringBuilder();
        dtCutOffDate = GetLastMonthEndDate();
        dtFromDate= GetFromDate();
        int index = 0;

        strReportName = string.Format(strReportName, GetTimeFormat(true,dtCutOffDate), GetTimeFormat(false,DateTime.Now));
        string strFilePath = string.Format("{0}{1}", GetReportGenerationPath(), strReportName);

        if (!File.Exists(strFilePath))
        {
            File.Create(strFilePath).Close();
        }

        foreach (DataColumn column in dtRecords.Columns)
        {
            csvGen.Append(column.ColumnName.ToUpper().Trim()).Append(delimiter);
        }
        index = csvGen.ToString().LastIndexOf(',');
        if (index > 0)
        {
            csvGen = csvGen.Remove(index,1);
        }
        csvGen.Append("\r\n");

        foreach (DataRow row in dtRecords.Rows)
        {
            foreach (DataColumn column in dtRecords.Columns)
            {
                csvGen.Append(row[column.ColumnName].ToString()).Append(delimiter);
            }
            csvGen.AppendLine();
            index = csvGen.ToString().LastIndexOf(',');
            if (index > 0)
            {
                csvGen = csvGen.Remove(index, 1);
            }
        }
        File.WriteAllText(strFilePath, csvGen.ToString());
    }
0

You can just append to the same file.

StreamWriter constructor allowing you to append

Other question regarding this

Community
  • 1
  • 1
Dietz
  • 578
  • 5
  • 14