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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM