简体   繁体   中英

Function for datatable to comma separated value

I am getting a datatable return type from one of my function

But as I have to display it on a multiline textbox so, I need a function that should be able to convert the datatable to a comma separated value to be displayed in a multiline textbox.

Can any suggest me such a function that would fulfill my need.

I had to write one myself a while ago. I wrote mine to write it out to a stream (since I was saving it to disk, but it should be trivial to change it to use a System.Text.StringBuilder (which I would use over concatenating strings for performance reasons).

public static void ToCsv(Stream stream, DataTable dataTable, bool includeColumnHeaders, char valueDelimiter, char textQualifier, string rowDelimiter)
    {
        StreamWriter sw = new StreamWriter(stream);
        string valueFormatString = (textQualifier + "{0}" + textQualifier).Trim();

        if (includeColumnHeaders)
        {  
            for(int i = 0; i < dataTable.Columns.Count; i++)
            {
                sw.Write(String.Format(valueFormatString, dataTable.Columns[i].ColumnName.Replace(textQualifier.ToString(), textQualifier.ToString() + textQualifier.ToString())));

                if (i != dataTable.Columns.Count - 1)
                    sw.Write(valueDelimiter);
            }

            sw.Write(rowDelimiter);
        }

        for(int i = 0; i < dataTable.Rows.Count; i++)            
        {
            for (int j = 0; j < dataTable.Rows[i].ItemArray.Length; j++)
            {
                sw.Write(String.Format(valueFormatString, dataTable.Rows[i][j].ToString().Replace(textQualifier.ToString(), textQualifier.ToString() + textQualifier.ToString())));

                if(j != dataTable.Rows[i].ItemArray.Length - 1)
                    sw.Write(valueDelimiter);
            }
            sw.Write(rowDelimiter);
        }

        sw.Flush();
    }

HTH, Brian

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM