导出一个C#的DataSet到文本文件 [英] Export a C# DataSet to a text file

查看:159
本文介绍了导出一个C#的DataSet到文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多在线的例子,如何填补从文本文件数据集,但我想要做的相反。我已经能够找到的唯一事情是的但似乎......不完整?

There are a lot of examples online of how to fill a DataSet from a text file but I want to do the reverse. The only thing I've been able to find is this but it seems... incomplete?

我想这是一个可读格式,而不仅仅是逗号在各行的列之间分隔,故不相等的间距,如果这是很有意义的。这里是我的意思的例子:

I want it to be in a readable format, not just comma delimited, so non-equal spacing between columns on each row if that makes sense. Here is an example of what I mean:

Column1          Column2          Column3
Some info        Some more info   Even more info
Some stuff here  Some more stuff  Even more stuff
Bits             and              bobs

请注意:我。只有我的DataSet所以没有必要担心多个数据表中的一个数据表

Note: I only have one DataTable within my DataSet so no need to worry about multiple DataTables.

编辑:当我说,可读我的意思是人类可读

When I said "readable" I meant human-readable.

先谢谢了。

推荐答案

这应该很好的空间了固定长度的字体的文本,但它意味着它将处理完整的DataTable两次(传1:找到每列最长文本,通过2:输出文本):

This should space out fixed length font text nicely, but it does mean it will process the full DataTable twice (pass 1: find longest text per column, pass 2: output text):

    static void Write(DataTable dt, string outputFilePath)
    {
        int[] maxLengths = new int[dt.Columns.Count];

        for (int i = 0; i < dt.Columns.Count; i++)
        {
            maxLengths[i] = dt.Columns[i].ColumnName.Length;

            foreach (DataRow row in dt.Rows)
            {
                if (!row.IsNull(i))
                {
                    int length = row[i].ToString().Length;

                    if (length > maxLengths[i])
                    {
                        maxLengths[i] = length;
                    }
                }
            }
        }

        using (StreamWriter sw = new StreamWriter(outputFilePath, false))
        {
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                sw.Write(dt.Columns[i].ColumnName.PadRight(maxLengths[i] + 2));
            }

            sw.WriteLine();

            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (!row.IsNull(i))
                    {
                        sw.Write(row[i].ToString().PadRight(maxLengths[i] + 2));
                    }
                    else
                    {
                        sw.Write(new string(' ', maxLengths[i] + 2));
                    }
                }

                sw.WriteLine();
            }

            sw.Close();
        }
    }

这篇关于导出一个C#的DataSet到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆