segunda-feira, 20 de julho de 2015

DataTableToCsv

using System.Data;
using System.Text;

namespace Lapuinka.Utils
{
    public class DataTableToCsv
    {
        public static StringBuilder ToCsv(DataTable table)
        {
            var result = new StringBuilder();
            for (var i = 0; i < table.Columns.Count; i++)
            {
                result.Append(table.Columns[i].Caption ?? table.Columns[i].ColumnName);
                result.Append(i == table.Columns.Count - 1 ? "\n" : ";");
            }

            foreach (DataRow row in table.Rows)
            {
                for (var i = 0; i < table.Columns.Count; i++)
                {
                    result.Append(row[i].ToString());
                    result.Append(i == table.Columns.Count - 1 ? "\n" : ";");
                }
            }

            return result;
        }
    }
}


Postar um comentário