我在数据集中有数据。如何将其导出到制表符分隔文件?
答案 0 :(得分:7)
var builder = new StringBuilder()
foreach(var row in dataSet.Tables.First().Rows)
{
foreach(var cell in row.ItemArray)
{
builder.Append(cell.ToString());
if(cell != row.Cells.Last())
builder.Append("\t");
}
builder.Append(Environment.NewLine);
}
var file = new FileStream(filePath);
var writer = new StreamWriter(file);
writer.Write(builder.ToString());
writer.Flush();
writer.Close();
答案 1 :(得分:4)
这里的问题相同。为你做得更好:
var builder = new StringBuilder();
foreach (DataRow row in dataSet.Tables.First().Rows) {
builder.AppendLine(String.Join("\t", row.ItemArray));
}
File.WriteAllText(filePath, builder.ToString());
它更紧凑,(可能)更快一点。
答案 2 :(得分:0)
答案 3 :(得分:0)
试试这个;
string updatefilePath = Server.MapPath("Files\\newoutput.PIPE");
StreamWriter sw = new StreamWriter(updatefilePath, false);
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write("|");
}
}
sw.Write(sw.NewLine);
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(row[i]))
{
sw.Write(row[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write("|");
}
}
sw.Write(sw.NewLine);
}
sw.Close();