从数据集导出到制表符分隔文件

时间:2010-12-16 20:23:10

标签: c# export-to-excel

我在数据集中有数据。如何将其导出到制表符分隔文件?

4 个答案:

答案 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)

试试这个:

http://www.codeproject.com/KB/aspnet/ExportClassLibrary.aspx

我希望您可以轻松地从数据集中获取数据表...

答案 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();