今天一朋友让我写了个asp.net生成htm的简单案例给他看看,顺便也和大家分享一下.
建一个htm模板 如下 将要替换的地方用$htmlformat[]表示
<
TABLE
height
="8"
cellSpacing
="0"
cellPadding
="0"
width
="256"
border
="0"
ms_1d_layout
="TRUE"
>
<
TR
>
<
TD
>
<
TABLE
id
="Table1"
height
="45"
cellSpacing
="1"
cellPadding
="1"
width
="300"
border
="1"
>
<
TR
>
<
TD
><
FONT
face
="宋体"
>
$htmlformat[0]
</
FONT
></
TD
>
</
TR
>
<
TR
>
<
TD
><
FONT
face
="宋体"
>
$htmlformat[1]
</
FONT
></
TD
>
</
TR
>
</
TABLE
>
</
TD
>
</
TR
>
</
TABLE
>
写一个类BuildHtm,这样可以便于在其他程序的调用,在这个类里写如下代码
public
string
Build(
string
title,
string
content)
//
htm模板上只两处要替换所在就定义两个参数

...
{
string strtitle=title;
string strcontent=content;
string[] format = new string[2];
StringBuilder htmltext=new StringBuilder();
StreamReader sr=new StreamReader(HttpContext.Current.Server.MapPath("Model.htm"),System.Text.Encoding.GetEncoding

("GB2312"));
string line;
while((line=sr.ReadLine())!=null)

...{
htmltext.Append(line);
}
sr.Close();
format[0]=strtitle;
format[1]=strcontent;
for( int i=0;i<2;i++)

...{
htmltext.Replace("$htmlformat["+i+"]", format[i]);
}
string StrDate=DateTime.Now.ToString("yyyyMMddhhmmss")+DateTime.Now.Millisecond.ToString();
string strhtml=StrDate+".htm";
StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath

(strhtml),false,System.Text.Encoding.GetEncoding("GB2312"));
sw.WriteLine(htmltext);
sw.Flush();
sw.Close();
return strhtml;//这边返回了生成的文件名,可以将它插入数据库,然后在绑定数据的时候在链接时绑定文件名
}
下面再要调用页面的.cs文件中写如下代码
BuildHtm bhtml
=
new
BuildHtm();
string
path
=
bhtml.Build(
this
.TextBox1.Text,
this
.TextBox2.Text);
//
这边的path返回的是一个文件名,当绑定链接的时候可以绑定这个文
件名.
代码下载路径
http://download.youkuaiyun.com/user/lem12/Asp.net%E7%94%9F%E6%88%90html