美美美

博客园 首页 新随笔 联系 订阅 管理

//使用方法 ExcelHelper.dataTableToCsv(dt,@"D:\1212.xls");System.Diagnostics.Process.Start(@"c:\1.xls"); //打开excel文件
public static void dataTableToCsv(DataTable table, string file)
{

string title = "";

FileStream fs = new FileStream(file, FileMode.OpenOrCreate);

//FileStream fs1 = File.Open(file, FileMode.Open, FileAccess.Read);

StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);

for (int i = 0; i < table.Columns.Count; i++)
{

title += table.Columns[i].ColumnName + "\t"; //栏位:自动跳到下一单元格

}

title = title.Substring(0, title.Length - 1) + "\n";

sw.Write(title);

foreach (DataRow row in table.Rows)
{

string line = "";

for (int i = 0; i < table.Columns.Count; i++)
{

line += row[i].ToString().Trim() + "\t"; //内容:自动跳到下一单元格

}

line = line.Substring(0, line.Length - 1) + "\n";

sw.Write(line);

}

sw.Close();

fs.Close();

}

posted on 2015-12-10 23:06  啸天美美  阅读(417)  评论(0编辑  收藏  举报