流导出excel在单元格内加换行符

flymouse007 2013-07-20 09:49:56
最近在做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();
}
...全文
6333 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
flymouse007 2013-07-20
  • 打赏
  • 举报
回复
引用 3 楼 Chinajiyong 的回复:
[quote=引用 2 楼 Chinajiyong 的回复:] 用(char)10试试
[/url][/quote] 已经实现了,是借鉴你给我发的这篇文章。不过也是后台定义数据控件,通过流输出,没有办法,做的东西得交了。 谢谢了,要结贴了,我分不多,给你吧。
flymouse007 2013-07-20
  • 打赏
  • 举报
回复
引用 3 楼 Chinajiyong 的回复:
[quote=引用 2 楼 Chinajiyong 的回复:] 用(char)10试试
http://blog.csdn.net/tiangaojie123abc/article/details/7900600[/quote] 奥 这篇文章我看了,不过他的思路应该是绑定到前台控件datalist或者datagrid之类的空间,然后生成根据空间导出的格式。
flymouse007 2013-07-20
  • 打赏
  • 举报
回复
引用 2 楼 Chinajiyong 的回复:
用(char)10试试
是在把我要换行的标签<br/>换成(char)10吗 我试试
EnForGrass 2013-07-20
  • 打赏
  • 举报
回复
引用 2 楼 Chinajiyong 的回复:
用(char)10试试
看看这篇文章对你也许有帮助http://blog.csdn.net/tiangaojie123abc/article/details/7900600
EnForGrass 2013-07-20
  • 打赏
  • 举报
回复
用(char)10试试
flymouse007 2013-07-20
  • 打赏
  • 举报
回复
我目前的实现方法还是看了一篇php解决单元格换行的文章得来的,不过效果不是太好,虽然实现了换行,不过打开后高度好像固定了,双击该单元格后,高度自动适应内容的高度。 他的思路是,在把某列有换行的单元格加上\r\t字符,并且这一列的开始和结束要加上"这个字符。 这是核心代码: strcontent = strcontent.Replace("<br/>", "\r\n"); strBuiler.Append("\""); strBuiler.Append(strcontent); strBuiler.Append("\""); 求各位大侠帮帮看看吧。

110,561

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧