在新工作表中将数据从datatable写入现有csv文件

时间:2014-02-06 08:51:25

标签: c# csv datatable worksheet

我正在尝试在c#中将数据从datatable写入cs文件。 问题是我想在现有csv文件的新工作表中编写数据表

我已经有了将数据从datatable写入新csv文件的功能。 有什么帮助吗?

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;  
    }  
}  

0 个答案:

没有答案
相关问题