因为
Excel
可以打开
html
文件,所以我们可以把
html
文件的内容输出到一个
xls
文件里,这样就实现了所见即所得的输出。
public void outputExcel()
{
string printUrl = "
要输出的报表文件
.aspx”; //
此文件就是一个输出数据表格的网页,可以是
html
也可以是
aspx
string printText = GetterUtil.GetUrlContent(printUrl);
Response.ContentEncoding = Encoding.UTF8;
Response.AddHeader("Content-Disposition", "attachment; filename=
输出文件名
.xls");
Response.Write(printText);
Response.End();
}
public static string GetUrlContent(string printUrl)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(printUrl);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
StringBuilder ret = new StringBuilder();
int bufferLengh = 8 * 1024; // 16K
char[] buf = new char[bufferLengh];
int len = sr.Read(buf, 0, bufferLengh);
while (len > 0)
{
ret.Append(new string(buf, 0, len));
len = sr.Read(buf, 0, bufferLengh);
}
return ret.ToString();
}