说明:NOT A SINGLE DataTable,Multiple DataTable From DataSet
如何导出数据集(多个数据表)到记事本。从c #
我的建议很简单,创建一个翻译器或下载一堆其他可用的库。
你最想去
public interfacte IExport
{
bool Export(Databale sometable);// this can also reference interface
//concrete implementation could also handle saving of file
}
然后调用一个具体类来实现该值,使用工厂模式、依赖注入等来提供具体类型。然后,您可以继续添加尽可能多的转换器来支持尽可能多的文件类型。
private void Write(System.Data.DataSet dts, string outputFilePath)
{
System.Data.DataTable dt = new System.Data.DataTable();
for (int z = 0; z < dts.Tables.Count; z++)
{
dt = dts.Tables[z];
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, true))
{
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();
}
}
}