日期:2014-05-18 浏览次数:21021 次
using System; using System.Text; using System.IO; namespace Test { public partial class XmlExcel : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //存放模板文件内容 string fileContent = string.Empty; //模板文件位置 string modleFileName = Server.MapPath(".") + "\\ExcelModleFile.xls"; //生成文件位置 string renderFileName = Server.MapPath(".") + "\\ExcelFile.xls"; //读出并保存模板文件内容 StreamReader sr = new StreamReader(modleFileName, System.Text.Encoding.GetEncoding("gb2312")); fileContent = sr.ReadToEnd(); sr.Close(); //循环生成数据行 StringBuilder sbRowsText = new StringBuilder(1024); sbRowsText.Append("<Row ss:AutoFitHeight=\"0\">"); sbRowsText.Append("<Cell ss:StyleID=\"s24\" ss:HRef=\""); //设置超链接地址 sbRowsText.Append("http://www.126.com/"); sbRowsText.Append("\"><Data ss:Type=\"String\">View</Data></Cell>"); sbRowsText.Append("<Cell ss:StyleID=\"s22\"><Data ss:Type=\"String\">"); //设置内容 sbRowsText.Append("Content"); sbRowsText.Append("</Data></Cell>"); sbRowsText.Append("</Row>"); //保存完整Excel内容的字符串 StringBuilder sbRender = new StringBuilder(); //获得模板内容 sbRender.Append(fileContent); //设置Excel数据行 sbRender.Replace(@"[RowCount]", "3"); //设置Excel标题 sbRender.Replace(@"[Header]", "Title"); //添加数据行 sbRender.Replace(@"[DataRows]", sbRowsText.ToString()); lblXml.Text = sbRender.ToString(); //将内容写入文件 StreamWriter sw = new StreamWriter(renderFileName); sw.Write(sbRender.ToString()); sw.Close(); //将文件输出到客户端 Response.Charset = "GB2312"; Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(renderFileName)); // 指定返回的是一个不能被客户端读取的流,必须被下载 Response.ContentType = "application/ms-excel"; // 把文件流发送到客户端 Response.WriteFile(renderFileName); Response.End(); } } }
------解决方案--------------------