.net操作word-1

来源:互联网 发布:比尔盖茨 院士 知乎 编辑:程序博客网 时间:2024/05/21 04:39

空网页

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>向Word文档中写入文字</title>
    <style type="text/css">
        .style1
        {
            border: medium double #E7E7E7;
            font-size: 10pt;
        }
    </style>
</head>
<body style="font-size: 10pt">
    <form id="form1" runat="server">
    <div>
        <table class="style1">
            <tr>
                <td>输入创建的文档名称</td>
                <td><asp:TextBox ID="txtDocName" runat="server" Width="150px" Text="Temp.doc"></asp:TextBox></td>
            </tr>
            <tr>
                <td>输入文档的内容</td>
                <td><asp:TextBox ID="txtDocContent" runat="server" Width="300px" Text="明日公司,编程词典" TextMode="MultiLine" Rows="5"></asp:TextBox></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <asp:Button ID="btnNew" runat="server" Text="创建Word文档" onclick="btnNew_Click"/>       
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>
后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Word = Microsoft.Office.Interop.Word;
using System.Threading;
using office = Microsoft.Office.Core;
using System.Reflection;

public partial class _Default : System.Web.UI.Page
{
    private Word.Application G_wa;//定义Word应用程序字段
    private object G_missing = System.Reflection.Missing.Value;//定义G_missing字段并添加引用
    object G_str_path;
   
    protected void Page_Load(object sender, EventArgs e)
    {
        G_str_path = Server.MapPath("./File") + "\\" + txtDocName.Text;//定义文件保存路径字段
    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        G_wa = new Word.Application();//创建Word应用程序对象
        Word.Document P_wd = G_wa.Documents.Add(ref G_missing, ref G_missing, ref G_missing, ref G_missing);//建立新文档
        Word.Range P_Range = P_wd.Paragraphs[1].Range;
        P_Range.Text = txtDocContent.Text;
        //保存Word文件
        P_wd.SaveAs(
            ref G_str_path,
            ref G_missing, ref G_missing, ref G_missing, ref G_missing,
            ref G_missing, ref G_missing, ref G_missing, ref G_missing,
            ref G_missing, ref G_missing, ref G_missing, ref G_missing,
            ref G_missing, ref G_missing, ref G_missing);
        ((Word._Application)G_wa.Application).Quit(ref G_missing, ref G_missing, ref G_missing);//退出应用程序
        Response.Write("<script>alert('成功创建Word文档!');</script>");//提示已经创建Word
    }
}

0 0