第一種方法:直接轉化一個頁面的方法
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("<p>寫入檔案出錯:" + 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("<p>組建檔案成功:" + 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("<p>讀取檔案出錯:" + 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("<p>寫入檔案出錯:" + 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("<p>組建檔案成功:" + fna);
上個圖吧