流导出excel在单元格内加换行符
最近在做excel文件生成时遇到单元给换行问题,查了资料解决的效果不是很好,我做的是从数据库中读取数据后,放到数据集里,通过流生成文件。代码如下:
public static void OutputExcelFile(System.Data.DataTable dt,string filedir, string filename)
{
string strPath = filedir + filename + ".xls";
strPath = System.Web.HttpContext.Current.Server.MapPath(strPath);
System.IO.FileInfo _fi = new System.IO.FileInfo(strPath);
if (!Directory.Exists(_fi.DirectoryName))//判断目录是否存在
{
Directory.CreateDirectory(_fi.DirectoryName);
}
if (System.IO.File.Exists(strPath))
System.IO.File.Delete(strPath);
//列名
System.Text.StringBuilder strBuiler = new StringBuilder();
for (int i = 0; i < dt.Columns.Count; i++)
{
strBuiler.Append(dt.Columns[i].ColumnName.ToString());
strBuiler.Append("\t");
}
strBuiler.Append("\r");
for (int j = 0; j < dt.Rows.Count; j++)
{
for (int x = 0; x < dt.Columns.Count; x++)
{
string strcontent= dt.Rows[j][x].ToString();
if (strcontent.Contains("<br/>"))
{
strcontent = strcontent.Replace("<br/>", "\r\n");
strBuiler.Append("\"");
strBuiler.Append(strcontent);
strBuiler.Append("\"");
}
else
strBuiler.Append(strcontent);
strBuiler.Append("\t");
}
strBuiler.Append("\r");
}
System.IO.StreamWriter f = System.IO.File.CreateText(strPath);
f.Close();
f.Dispose();
System.IO.StreamWriter f2 = new System.IO.StreamWriter(strPath, true, System.Text.Encoding.Default);
f2.WriteLine(strBuiler.ToString());
f2.Close();
f2.Dispose();
}