Export a C# DataSet to a text file(将 C# 数据集导出到文本文件)
问题描述
网上有很多关于如何从文本文件中填充数据集的示例,但我想做相反的事情.我唯一能找到的是 this 但看起来……不完整?
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# 数据集导出到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 C# 数据集导出到文本文件
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01