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 窗体设计器生成的代码#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/** <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);

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

public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
}
}3.注意点:
在上面的代码中关键的地方就是以下两行代码:
Response.Charset = "utf-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); 第一行代码设定浏览器所使用的编码为utf-8,第二行代码设定的是word和excel的编码,因为word和excel的编码一般使用的是gb2312编码,不一定和浏览器(一般默认utf-8)的一致,这也是许多网友问题所在!

另外:前台页面需要修改(增加红色部分):<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true" CodeBehind="Html2Word.aspx.cs" Inherits="GridViewTest.Html2Word" %>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

icewizardry

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值