第一种方法:直接转化一个页面的方法
public static bool CreateList(string url, string fna) { bool ok; //准备生成 string strHtml; StreamReader sr = null; //用来读取流 StreamWriter sw = null; //用来写文件 Encoding code = Encoding.GetEncoding("utf-8"); //定义编码 //构造web请求,发送请求,获取响应 WebRequest HttpWebRequest = null; WebResponse HttpWebResponse = null; HttpWebRequest = WebRequest.Create(url); HttpWebResponse = HttpWebRequest.GetResponse(); //获得流 sr = new StreamReader(HttpWebResponse.GetResponseStream(), code); strHtml = sr.ReadToEnd(); //写入文件 try { sw = new StreamWriter(fna, false, code); sw.Write(strHtml); sw.Flush(); ok = true; } catch (Exception ex) { HttpContext.Current.Response.Write("写入文件出错:" + ex.Message); HttpContext.Current.Response.End(); ok = false; } finally { sw.Close(); } return ok; }
调用
string url = @"http://localhost:15598/OA/PublicGV.aspx?id=14"; //html页面文件名 string fna = Server.MapPath("html") + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString() + ".html"; if (aspxtohtml.CreateList(url, fna)) { Response.Write("生成文件成功:" + fna); }
第二种方法是用一个html模板生成一个html页面,模版里面有对应的标签,可以从数据库和别的地方取数据,填写这个标签,生成一个html页面,这个方法在很多新闻系统里有用到
private string CreateDetailPage(string EventID,string EventTitle, string EventBody, string EventTime, string EventStat) { //模版所有路径、模版文件名、生成的文件路径、生成的文件名 string path, temp, htmlfilepath,htmlfilename; path = Server.MapPath(""); temp = Server.MapPath("testhtml.htm"); htmlfilepath = path; htmlfilename = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString() + ".html"; //读模版 Encoding code = Encoding.GetEncoding("gb2312"); StreamReader sr = null; StreamWriter sw = null; string str = ""; try { sr = new StreamReader(temp, code); str = sr.ReadToEnd(); // 读取文件 } catch (Exception exp) { HttpContext.Current.Response.Write("读取文件出错:" + exp.Message); HttpContext.Current.Response.End(); sr.Close(); } // 替换内容 // 对应模版里的设置要修改 str = str.Replace("re_symbol_EventID", EventID); str = str.Replace("re_symbol_EventTitle", EventTitle); str = str.Replace("re_symbol_EventBody", EventBody); str = str.Replace("re_symbol_EventTime", EventTime); str = str.Replace("re_symbol_EventStat", EventStat); // 写文件 try { sw = new StreamWriter(htmlfilepath + "//" + htmlfilename, false, code); sw.Write(str); sw.Flush(); } catch (Exception ex) { HttpContext.Current.Response.Write("
写入文件出错:" + ex.Message); HttpContext.Current.Response.End(); } finally { sw.Close(); } return htmlfilename; }
调用的时候这样:
int i; i = GridView1.SelectedIndex; if (i == null || i==-1) i = 0; string EventID, EventTitle, EventBody, EventTime, EventStat; EventID=GridView1.Rows[i].Cells[0].Text; EventTitle=GridView1.Rows[i].Cells[1].Text; EventBody=GridView1.Rows[i].Cells[2].Text; EventTime=GridView1.Rows[i].Cells[3].Text; EventStat=GridView1.Rows[i].Cells[4].Text; //生成文件,返回文件名 string fna; fna=CreateDetailPage(EventID, EventTitle, EventBody, EventTime, EventStat); Response.Write("生成文件成功:" + fna);
上个图吧