将网页内容转换成word或excel文档的方法(c#.net)

最近看到好多网友关于使用c#.net实现网页内容转换成word或excel时时常出现乱码的问题,现将如何转换做个详细的介绍。
1.转换方法:
        一般用HTTP的Header,在header里设置几个关键字让IE知道这是什么类型,从而正确打开。
2.C#源码:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace word
{
    
/// <summary>
    
/// htm2doc 的摘要说明。
    
/// </summary>

    public class htm2doc : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.Button Button1;
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{        
            
// 在此处放置用户代码以初始化页面
        }

        
public void ExpertControl(System.Web.UI.Control source, DocumentType type)

        
{
            
//设置Http的头信息,编码格式
            if (type == DocumentType.Excel)
            
{
                
//Excel
                Response.AppendHeader("Content-Disposition","attachment;filename=result.xls");
                Response.ContentType 
= "application/ms-excel";
            }

            
else if (type == DocumentType.Word)
            
{
                
//Word
                Response.AppendHeader("Content-Disposition","attachment;filename=result.doc");
                Response.ContentType 
= "application/ms-word";
            }

            Response.Charset 
= "utf-8";   
            Response.ContentEncoding 
= System.Text.Encoding.GetEncoding("gb2312");
            
//关闭控件的视图状态
            source.Page.EnableViewState =false;   
            
//初始化HtmlWriter
            System.IO.StringWriter writer = new System.IO.StringWriter() ;
            System.Web.UI.HtmlTextWriter htmlWriter 
= new System.Web.UI.HtmlTextWriter(writer);
            source.RenderControl(htmlWriter);
            
//输出
            Response.Write(writer.ToString());
            Response.End();
        }

        
//文档类型枚举
        public enum DocumentType
        
{
            Word,
            Excel
        }

        
Web 窗体设计器生成的代码           //在web窗体中添加一个按钮使用该方法
        
private void Button1_Click(object sender, System.EventArgs e)
        
{
                ExpertControl(
this, DocumentType.Word);
        }

    }

}
3.注意点:
        在上面的代码中关键的地方就是以下两行代码:
     Response.Charset = "utf-8";   
     Response.ContentEncoding 
= System.Text.Encoding.GetEncoding("gb2312");
        第一行代码设定浏览器所使用的编码为utf-8,第二行代码设定的是word和excel的编码,因为word和excel的编码一般使用的是gb2312编码,不一定和浏览器(一般默认utf-8)的一致,这也是许多网友问题所在!
4.结束语
       在asp.net中将datagrid中的内容转换为word或excel的方法大致是一样的,可能我在后面的随笔中会写一下!与大家分享。
posted on 2007-01-16 23:28  虞山居士  阅读(5117)  评论(2编辑  收藏  举报