.NET DataTable中的数据导出到Excel

/// <summary>
/// DataTable中的数据导出到Excel并下载
/// </summary>
/// <param name="dataTable">要导出的DataTable</param>
/// <param name="FileType">类型</param>
/// <param name="s_FileName">Excel的文件名</param>
public static string ExportExcelByDataTable(DataTable dataTable, string excelHeader, string path)
{
//文件存放路径
string FilePath = string.Empty;
String Tpath = "/" + DateTime.Now.ToString("yyyyMMdd").Substring(0, 6) + "/";
if (!string.IsNullOrEmpty(path))
{
FilePath = path;
}
else
{
FilePath = HttpContext.Current.Server.MapPath("~/UploadFile" + Tpath);
}


DirectoryInfo di = new DirectoryInfo(FilePath);
if (!di.Exists) { di.Create(); }

//文件名
string fname = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string FileName = FilePath + fname + ".xls";

string loadPath = string.Empty;
if (!string.IsNullOrEmpty(path))
{
loadPath = path + fname + ".xls";
}
else
{
loadPath = "/UploadFile" + Tpath + fname + ".xls";
}

FileStream objFileStream;
StreamWriter objStreamWriter;
string strLine = string.Empty;
objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
objStreamWriter = new StreamWriter(objFileStream, Encoding.Unicode);


if (!string.IsNullOrEmpty(excelHeader))
{
string[] colHead = excelHeader.Split(',');
for (int i = 0; i < colHead.Length; i++)
{
//写列标题
strLine += colHead[i].ToString() + "\t";
}
//strLine += "\n";
objStreamWriter.WriteLine(strLine);
}
strLine = string.Empty;

for (int i = 0; i < dataTable.Rows.Count; i++)
{
int column = dataTable.Columns.Count;
for (int j = 0; j < dataTable.Columns.Count; j++)
{
//if (j == (column - 1))
//{
// strLine += dataTable.Rows[i][j].ToString() + "\n";
//}
//else
//{
if (dataTable.Rows[i][j].ToString() == "")
{
strLine += "\t";
}
else
{
strLine += dataTable.Rows[i][j].ToString() + "\t";
}
//}
}
//写内容
objStreamWriter.WriteLine(strLine);
strLine = string.Empty;
}
objStreamWriter.Close();
objFileStream.Close();
return loadPath; //返回生成文件的路径

}

posted on 2018-12-04 17:16  随,风  阅读(141)  评论(0编辑  收藏  举报

导航