gpt4 book ai didi

c# - 在 C# Windows 应用程序中将两个数据表导入一个 csv 文件

转载 作者:行者123 更新时间:2023-11-30 21:54:29 24 4
gpt4 key购买 nike

我有两个数据表。一个包含雇主姓名,另一个包含员工详细信息。我需要将这两个数据表放入 csv 文件。

格式如下:

EmployerName EmployerCode
XXXXXXXxxx YYYYYYYY
EmployeeId EmployeeName EmployeeCode
1 AAAAAAAA AA1
2 BBBBB BB2
.............

我的代码如下:但是它只会导出一个数据表。

public void CreateCSVFile(DataTable dtDataTable, string strFilePath)
{
StreamWriter sw = new StreamWriter(strFilePath, false);
for (int i = 0; i < dtDataTable.Columns.Count; i++)
{
sw.Write(dtDataTable.Columns[i]);
if (i < dtDataTable.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dtDataTable.Rows)
{
for (int i = 0; i < dtDataTable.Columns.Count; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
string value = dr[i].ToString();
if (value.Contains(','))
{
value = String.Format("\"{0}\"", value);
sw.Write(value);
}
else
{
sw.Write(dr[i].ToString());
}
}
if (i < dtDataTable.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();

}

有人可以帮忙吗?

最佳答案

只需将方法的第一行更改为:

StreamWriter sw = new StreamWriter(strFilePath, true);

然后它附加到文件。

然后你应该为两个数据表调用你的方法:

var filePath = @"d:\export.csv";
CreateCSVFile(yourDataTable1, filePath);
CreateCSVFile(yourDataTable2, filePath);

StreamWriter(String path, Boolean append)
Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

Parameters:

path: The complete file path to write to.

append: true to append data to the file; false to overwrite the file. If the specified file does not exist, this parameter has no effect, and the constructor creates a new file.

关于c# - 在 C# Windows 应用程序中将两个数据表导入一个 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33062501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com