创建word文档,并输出文本

    1) 首先添加"COM“引用

    打开"添加引用"对话框,选中"COM"选项,添加名为"Microsoft Word 11.0 Object Library"的引用。成功添加后,在"References"中多出了三个引用,分别为"Microsoft.Office..Core" 、"VBIDE"和"Word".

   2)编写代码

/*
 * 文件名:WriteToWordDemo.cs
 * 说明:创建Word文档,并写入内容
 * 时间:2008-9-20
 * 开发环境:Visual studio 2008
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;

namespace WriteToWordDemo
{
    class WriteToWordDemo
    {
        static void Main(string[] args)
        {
            object path;    // 文件路径
            string content; // 写入文件的内容

            Application wordApp; // word应用程序对象
            Document wordDoc;    // word文档对象

            path = "c://myWord.doc";
            wordApp = new Application();

            if (File.Exists((string)path))  // 如果文件存在,则删除
            {
                File.Delete((string)path);
            }

            object nothing = Missing.Value;
            wordDoc = wordApp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing);

            content = "Write content to word document.";
            wordDoc.Paragraphs.Last.Range.Text = content; // 写入内容

            object format = WdSaveFormat.wdFormatDocument; // word文档保存格式
            wordDoc.SaveAs(ref path, ref format, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
                           ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
                           ref nothing, ref nothing);


            wordDoc.Close(ref nothing, ref nothing, ref nothing); // 关闭word文档对象
            wordApp.Quit(ref nothing, ref nothing, ref nothing);  // 关闭word应用程序对象

            Console.WriteLine("over.");
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值