将C#DataSet导出到文本文件 [英] Export a C# DataSet to a text file
问题描述
在线上有很多关于如何从文本文件填充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中只有一个DataTable,所以没有必要担心多个DataTable。
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屋!