导出TXT
在winform 中如何将datagrid导出TXT
------解决方案--------------------给你一个我原来写的参才一下吧,代码比较多些,你慢慢看吧:
/// <summary>
/// 把DataTable的显示内容存成文本文件。
/// </summary>
/// <param name= "fileName "> Text文件名字 </param>
/// <param name= "srcTable "> 源表 </param>
/// <param name= "ColTitle "> 列的别名 </param>
/// <param name= "InfoMessage "> 处理过程的返回信息。 </param>
/// <returns> </returns>
public bool SaveAsText(string fileName, DataTable srcTable, Hashtable ColTitle, out string InfoMessage)
{
//TODO:文本文件
InfoMessage = null;
try
{
if (srcTable != null)
{
System.IO.StreamWriter w = new System.IO.StreamWriter(fileName);
//准备写表头
string strContent = " ";
for (int i = 0; i < srcTable.Columns.Count; i++)
{
string colName = srcTable.Columns[i].ColumnName;
if (ColTitle != null && ColTitle.Contains(colName.ToLower()) && ColTitle[colName.ToLower()] is TableCol && ColTitle[colName.ToLower()].ToString().Length > 0)
{
colName = ColTitle[colName.ToLower()].ToString();
if (strContent != " " )
{
strContent = strContent + "\t " + colName;
}
else
{
strContent = colName;
}
}
}
w.WriteLine(strContent);//写表头
//准备写内容
for (int i = 0; i < srcTable.Rows.Count; i++)
{
strContent = " ";
for (int j = 0; j < srcTable.Columns.Count; j++)
{
string colName = srcTable.Columns[j].ColumnName;
if (ColTitle != null && ColTitle.Contains(colName.ToLower()) && ColTitle[colName.ToLower()] is TableCol && ColTitle[colName.ToLower()].ToString().Length > 0)
{
if (strContent != " ")
{
strContent = strContent + "\t " + srcTable.Rows[i][j].ToString();
}
else
{
strContent = strContent + srcTable.Rows[i][j].ToString();
}
}
}
w.WriteLine(strContent);
}
w.Flush();
w.Close();
return true;
}
}
catch (Exception ex)
{
InfoMessage = ex.Message;
}
return false;
}