DataSet导出Html

      最近由于工作需要,将得到的DataSet中的数据导出到网页文件中,一直在找WinForm下怎么可以方便快捷的实现这个功能,但是找了很久都没有结果。最后还是使用最古老的办法吧!
      实现思路:
            1.建立一个HTML模板文件,在里面给需要动态修改的地方做好标记;
            2.读取HTML模板文件,用一个变量x保存;
            3.遍历DataSet集合中的数据,将Html标签并接;
            4.x中的标记逐一替换;
            5.将x保存;

      下面给出相应的HTML模板文件,以及程序代码。
HTML模板文件:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    
<title>{title}</title>
</head>
<body>
    
<table width="100%" border="1" cellpadding="2" cellspacing="1">
        
<thead>
            
<tr>
                {thead}
            
</tr>
        
</thead>
        
<tbody>
            {tbody}
        
</tbody>
    
</table>
</body>
</html>

程序代码:
   /// <summary>
        
/// 导出HTML文件
        
/// </summary>
        
/// <param name="ds">DataSet对象</param>
        
/// <param name="tplFilePath">模板文件路径</param>
        
/// <param name="saveFilePath">文件导出路径</param>
        
/// <param name="title">HTML标题</param>
        
/// <returns>布尔类型</returns>

        public bool ExportHtml(DataSet ds, string tplFilePath, string saveFilePath, string title)
        
{
            
if (ds.Tables[0].Rows.Count <= 0throw new Exception("DataSet为空");

            
bool result = false;
            StringBuilder sb 
= new StringBuilder();

            
try
            
{
                
string _tplContent = string.Empty;
                
using (StreamReader sr = new StreamReader(tplFilePath))
                
{
                    _tplContent 
= sr.ReadToEnd();
                }



                
//title
                _tplContent = _tplContent.Replace("{title}", title);

                
//thead
                sb.Remove(0, sb.Length);
                
foreach (DataColumn col in ds.Tables[0].Columns)
                
{
                    sb.AppendFormat(
"<TH>{0}</TH>", col.Caption);
                }

                _tplContent 
= _tplContent.Replace("{thead}", sb.ToString());

                
//tbody
                sb.Remove(0, sb.Length);
                
foreach (DataRow row in ds.Tables[0].Rows)
                
{
                    sb.Append(
"<TR>");
                    
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                    
{
                        sb.AppendFormat(
"<TD nowrap=\"nowrap\">{0}</TD>", row[i].ToString());
                    }

                    sb.Append(
"</TR>");
                }

                _tplContent 
= _tplContent.Replace("{tbody}", sb.ToString());

                
using (StreamWriter sw = new StreamWriter(saveFilePath, false, System.Text.Encoding.UTF8))
                
{
                    sw.WriteLine(_tplContent);
                }

            }

            
catch (Exception ex)
            
throw ex; }
            
finally
            
{ sb = null; }

            
return result;
        }
posted @ 2009-09-15 20:56  ajayumi  阅读(324)  评论(0)    收藏  举报