c# datatable 如何转CSV文件

 public void DataTableToCSV(DataTable dtCSV, string csvFileFullName, bool writeHeader, 
            string delimeter)
        {
            if ((null != dtCSV) && (dtCSV.Rows.Count > 0))
            {
                //Delete the old one
                if (File.Exists(csvFileFullName))
                {
                    File.Delete(csvFileFullName);
                }

                string tmpLineText = "";

                //Write header
                if (writeHeader)
                {
                    tmpLineText = "";
                    for (int i = 0; i < dtCSV.Columns.Count; i++)
                    {
                        string tmpColumnValue = dtCSV.Columns[i].ColumnName;
                        if (tmpColumnValue.Contains(delimeter))
                        {
                            tmpColumnValue = "\"" + tmpColumnValue + "\"";
                        }

                        if (i == dtCSV.Columns.Count - 1)
                        {
                            tmpLineText += tmpColumnValue;
                        }
                        else
                        {
                            tmpLineText += tmpColumnValue + delimeter;
                        }
                    }
                    WriteFile(csvFileFullName, tmpLineText);
                }

                //Write content
                for (int j = 0; j < dtCSV.Rows.Count; j++)
                {
                    tmpLineText = "";
                    for (int k = 0; k < dtCSV.Columns.Count; k++)
                    {
                        string tmpRowValue = dtCSV.Rows[j][k].ToString();
                        if (tmpRowValue.Contains(delimeter))
                        {
                            tmpRowValue = "\"" + tmpRowValue + "\"";
                        }

                        if (k == dtCSV.Columns.Count - 1)
                        {
                            tmpLineText += tmpRowValue;
                        }
                        else
                        {
                            tmpLineText += tmpRowValue + delimeter;
                        }
                    }
                    WriteFile(csvFileFullName, tmpLineText);
                }
            }
        }

        private void WriteFile(string fileFullName, string message)
        {
            using (StreamWriter sw = new StreamWriter(fileFullName, true, Encoding.UTF8))
            {
                sw.WriteLine(message);
            }
        }

 

posted @ 2016-12-08 11:14  白羽轻飘  阅读(3008)  评论(0编辑  收藏  举报