출처 : http://stackoverflow.com/questions/4959722/c-sharp-datatable-to-csv#4959869






 .net = 3.5

StringBuilder sb = new StringBuilder();

 

string[] columnNames = dt.Columns.Cast<DataColumn>().

                                    Select(column => column.ColumnName).

                                    ToArray();

sb.AppendLine(string.Join(",", columnNames));

 

foreach (DataRow row in dt.Rows)

{

    string[] fields = row.ItemArray.Select(field => field.ToString()).

                                    ToArray();

        sb.AppendLine(string.Join(",", fields));

}

 

File.WriteAllText("test.csv", sb.ToString());




.net >= 4.5

private bool DataTableToCSV(DataTable dt, string filePath, Encoding encoding = null)

{

    bool rtn = false;

    try

    {

        StringBuilder sb = new StringBuilder();

 

        IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().

                                            Select(column => column.ColumnName);

        sb.AppendLine(string.Join(",", columnNames));

 

        foreach (DataRow row in dt.Rows)

        {

            IEnumerable<string> fields = row.ItemArray.Select(field =>

                string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));

            sb.AppendLine(string.Join(",", fields));

        }

 

        File.WriteAllText(filePath, sb.ToString(), (encoding == null ? Encoding.UTF8 : encoding));

 

        rtn = true;

    }

    catch (Exception x)

    {

        Console.WriteLine(x.Message);

 

    }

 

    return rtn;

}






Posted by motolies

댓글을 달아 주세요