由于项目需要,以前是做b/s开发的先做c/s开发.其中就有Excel导出模块.在往上找了很多资料都是挺凌乱的
我整理了一下,在此分享.(有些代码片段来自他人,在此感谢)
View Code
public static bool haha(DataSet ds, string filenames)
{
try
{
string FileName = filenames;// "d:\\abc.xls";
DataTable dt = ds.Tables[0];
FileStream objFileStream;
StreamWriter objStreamWriter;
string strLine = "";
objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);
for (int i = 0; i < dt.Columns.Count; i++)
{
strLine = strLine + dt.Columns[i].ColumnName.ToString() + Convert.ToChar(9);
}
objStreamWriter.WriteLine(strLine);
strLine = "";
for (int i = 0; i < dt.Rows.Count; i++)
{
strLine = strLine + (i + 1) + Convert.ToChar(9);
for (int j = 1; j < dt.Columns.Count; j++)
{
strLine = strLine + dt.Rows[i][j].ToString() + Convert.ToChar(9);
}
objStreamWriter.WriteLine(strLine);
strLine = "";
}
objStreamWriter.Close();
objFileStream.Close();
return true;
}
catch (Exception)
{
return false;
throw;
}
}