当前位置: 首页 > article >正文

使用com组件编辑word

 一个普通的窗体应用,6个button

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MsWord = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;
using System.IO;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace wordcomtest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        public static class common
        {
             public static MsWord.Application oWordApplic;//a reference to Wordapplication
            public static MsWord.Document oDoc;//a reference to thedocument
            public static string doc_file_name = Directory.GetCurrentDirectory() + @"\content.doc";

        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            try
            {
                
                if (File.Exists(common.doc_file_name))
                {
                    File.Delete(common.doc_file_name);
                }
                common.oWordApplic = new MsWord.Application();
                object missing = System.Reflection.Missing.Value;
            }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message);
            }
            try
            { }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                MsWord.Range curRange;
                object curTxt;
                int curSectionNum = 1;
                common.oDoc = common.oWordApplic.Documents.Add();
                common.oDoc.Activate();
                //Console.WriteLine(" 正在生成文档小节");
                object section_nextPage = MsWord.WdBreakType.wdSectionBreakNextPage;
                object page_break = MsWord.WdBreakType.wdPageBreak;
                //添加三个分节符,共四个小节
                for (int si = 0; si < 2; si++)
                {
                    common.oDoc.Paragraphs[1].Range.InsertParagraphAfter();
                    common.oDoc.Paragraphs[1].Range.InsertBreak(ref section_nextPage);
                    
                 }
            }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {

            try
            {
                
                int curSectionNum = 1;
                var curRange = common.oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curRange.Select();
                string one_str, key_word;
                //摘要的文本来自 abstract.txt 文本文件
                StreamReader file_abstract = new StreamReader("abstract.txt");
                common.oWordApplic.Options.Overtype = false;//overtype 改写模式
                MsWord.Selection currentSelection = common.oWordApplic.Selection;
                if (currentSelection.Type == MsWord.WdSelectionType.wdSelectionNormal)
                {
                    one_str = file_abstract.ReadLine();//读入题目
                    currentSelection.TypeText(one_str);
                    currentSelection.TypeParagraph(); //添加段落标记
                    currentSelection.TypeText(" 摘要");//写入" 摘要" 二字
                    currentSelection.TypeParagraph(); //添加段落标记
                    key_word = file_abstract.ReadLine();//读入题目
                    one_str = file_abstract.ReadLine();//读入段落文本
                    while (one_str != null)
                    {
                        currentSelection.TypeText(one_str);
                        currentSelection.TypeParagraph(); //添加段落标记
                        one_str = file_abstract.ReadLine();
                    }
                    currentSelection.TypeText(" 关键字:");
                    currentSelection.TypeText(key_word);
                    currentSelection.TypeParagraph(); //添加段落标记
                }
                file_abstract.Close();
            }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                
                int curSectionNum = 3;
                common.oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range.Select();
                Range curRange = common.oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                Console.WriteLine(" 正在设置标题样式");
                object wdFontSizeIndex;
                wdFontSizeIndex = 14;//此序号在 word 中的编号是格式 > 显示格式 > 样式和格式 > 显示
                                     //14 即是标题一一级标题:三号黑体。
                common.oWordApplic.ActiveDocument.Styles.get_Item(ref wdFontSizeIndex).ParagraphFormat.Alignment =
                MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                common.oWordApplic.ActiveDocument.Styles.get_Item(ref wdFontSizeIndex).Font.Name = " 黑体";
                common.oWordApplic.ActiveDocument.Styles.get_Item(ref wdFontSizeIndex).Font.Size = 16;//三号
                wdFontSizeIndex = 15;//15 即是标题二二级标题:小三号黑体。
                common.oWordApplic.ActiveDocument.Styles.get_Item(ref wdFontSizeIndex).Font.Name = " 黑体";
                common.oWordApplic.ActiveDocument.Styles.get_Item(ref wdFontSizeIndex).Font.Size = 15;//小三
                                                                                               //用指定的标题来设定文本格式
                object Style1 = MsWord.WdBuiltinStyle.wdStyleHeading1;//一级标题:三号黑体。
                object Style2 = MsWord.WdBuiltinStyle.wdStyleHeading2;//二级标题:小三号黑体。
                common.oDoc.Sections[curSectionNum].Range.Select();
                
                var currentSelection = common.oWordApplic.Selection;
                //读入第一章文本信息
                StreamReader file_content = new StreamReader("content.txt");
                var one_str = file_content.ReadLine();//一级标题
                currentSelection.TypeText(one_str);
                currentSelection.TypeParagraph(); //添加段落标记
                one_str = file_content.ReadLine();//二级标题
                currentSelection.TypeText(one_str);
                currentSelection.TypeParagraph(); //添加段落标记
                one_str = file_content.ReadLine();//正文
                while (one_str != null)
                {
                    currentSelection.TypeText(one_str);
                    currentSelection.TypeParagraph(); //添加段落标记
                    one_str = file_content.ReadLine();//正文
                     }
                file_content.Close();
                //段落的对齐方式
                curRange = common.oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curRange.set_Style(ref Style1);
                common.oDoc.Sections[curSectionNum].Range.Paragraphs[1].Alignment =
                MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                curRange = common.oDoc.Sections[curSectionNum].Range.Paragraphs[2].Range;
                curRange.set_Style(ref Style2);
                //第一章正文文本格式
                for (int i = 3; i < common.oDoc.Sections[curSectionNum].Range.Paragraphs.Count; i++)
                {
                    curRange = common.oDoc.Sections[curSectionNum].Range.Paragraphs[i].Range;
                    curRange.Select();
                    curRange.Font.Name = " 宋体";
                    curRange.Font.Size = 12;
                    common.oDoc.Sections[curSectionNum].Range.Paragraphs[i].LineSpacingRule =
                    MsWord.WdLineSpacing.wdLineSpaceMultiple;
                    //多倍行距,1.25 倍,这里的浮点值是以 point 为单位的,不是行距的倍数
                    common.oDoc.Sections[curSectionNum].Range.Paragraphs[i].LineSpacing = 15f;
                    common.oDoc.Sections[curSectionNum].Range.Paragraphs[i].IndentFirstLineCharWidth(2);
                }
            }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                
                object missing = System.Reflection.Missing.Value;
                //设置页脚 section 1 摘要
                int curSectionNum = 1;
                common.oDoc.Sections[curSectionNum].Range.Select();
                //进入页脚视图
                common.oWordApplic.ActiveWindow.ActivePane.View.SeekView =
                MsWord.WdSeekView.wdSeekCurrentPageFooter;
                common.oDoc.Sections[curSectionNum].
                Headers[MsWord.WdHeaderFooterIndex.wdHeaderFooterPrimary].
                Range.Borders[MsWord.WdBorderType.wdBorderBottom].LineStyle =
                MsWord.WdLineStyle.wdLineStyleNone;
                common.oWordApplic.Selection.HeaderFooter.PageNumbers.RestartNumberingAtSection = true;
                common.oWordApplic.Selection.HeaderFooter.PageNumbers.NumberStyle
                = MsWord.WdPageNumberStyle.wdPageNumberStyleUppercaseRoman;
                common.oWordApplic.Selection.HeaderFooter.PageNumbers.StartingNumber = 1;
                //切换到文档
                common.oWordApplic.ActiveWindow.ActivePane.View.SeekView =
                MsWord.WdSeekView.wdSeekMainDocument;
                //Console.WriteLine(" 正在设置第二节目录页眉内容");
                //设置页脚 section 2 目录
                curSectionNum = 2;
                common.oDoc.Sections[curSectionNum].Range.Select();
                

                //进入页脚视图
                common.oWordApplic.ActiveWindow.ActivePane.View.SeekView =
                MsWord.WdSeekView.wdSeekCurrentPageFooter;
                common.oDoc.Sections[curSectionNum].
                Headers[MsWord.WdHeaderFooterIndex.wdHeaderFooterPrimary].
                Range.Borders[MsWord.WdBorderType.wdBorderBottom].LineStyle =
                MsWord.WdLineStyle.wdLineStyleNone;
                common.oWordApplic.Selection.HeaderFooter.PageNumbers.RestartNumberingAtSection = false;
                common.oWordApplic.Selection.HeaderFooter.PageNumbers.NumberStyle
                = MsWord.WdPageNumberStyle.wdPageNumberStyleUppercaseRoman;
                //oWordApplic.Selection.HeaderFooter.PageNumbers.StartingNumber = 1;
                //切换到文档
                common.oWordApplic.ActiveWindow.ActivePane.View.SeekView =
                MsWord.WdSeekView.wdSeekMainDocument;
                //第一章页眉页码设置
                curSectionNum = 3;
                common.oDoc.Sections[curSectionNum].Range.Select();
                //切换入页脚视图
                common.oWordApplic.ActiveWindow.ActivePane.View.SeekView =
                MsWord.WdSeekView.wdSeekCurrentPageFooter;
                var currentSelection = common.oWordApplic.Selection;
                var curRange = currentSelection.Range;
                //本节页码不续上节
                common.oWordApplic.Selection.HeaderFooter.PageNumbers.RestartNumberingAtSection = true;
                //页码格式为阿拉伯
                common.oWordApplic.Selection.HeaderFooter.PageNumbers.NumberStyle
                = MsWord.WdPageNumberStyle.wdPageNumberStyleArabic;
                //起如页码为 1
                common.oWordApplic.Selection.HeaderFooter.PageNumbers.StartingNumber = 1;
                //添加页码域
                object fieldpage = MsWord.WdFieldType.wdFieldPage;
                common.oWordApplic.Selection.Fields.Add(common.oWordApplic.Selection.Range,
                ref fieldpage, ref missing, ref missing);
                //居中对齐
                common.oWordApplic.Selection.ParagraphFormat.Alignment =
                MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                //本小节不链接到上一节
                common.oDoc.Sections[curSectionNum].Headers[Microsoft.Office.Interop.
                Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].LinkToPrevious = false;
                //切换入正文视图

                common.oWordApplic.ActiveWindow.ActivePane.View.SeekView =
                MsWord.WdSeekView.wdSeekMainDocument;

                
            }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message);
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            try
            {

                //common.oDoc.Fields[1].Update();
                
                //保存文档
                //Console.WriteLine(" 正在保存 Word 文档");
                //string doc_file_name = Directory.GetCurrentDirectory() + @"\content.doc";
                object fileName;
                fileName = common.doc_file_name;
                common.oDoc.SaveAs(ref fileName);
                common.oDoc.Close();
                //释放 COM 资源
                System.Runtime.InteropServices.Marshal.ReleaseComObject(common.oDoc);
                common.oDoc = null;
                common.oWordApplic.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(common.oWordApplic);
                common.oWordApplic = null;


                
                Spire.Doc.Document document = new Spire.Doc.Document(@"content.doc");
                Spire.Doc.Section section = document.AddSection();
                Spire.Doc.HeaderFooter footer = document.Sections[0].HeadersFooters.Footer;

                //Add text and image to the footer
                Spire.Doc.Documents.Paragraph paragraph = footer.AddParagraph();
                DocPicture footerImage = paragraph.AppendPicture(Image.FromFile("whu.png"));
                TextRange TR = paragraph.AppendText("Supported and Hosted by the non-profit Wikimedia Foundation.");

                //Format the text and image
                paragraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left;
                TR.CharacterFormat.FontName = "Calibri";
                TR.CharacterFormat.Bold = true;


                //添加一个Shape,并设置其大小和样式
                Spire.Doc.Documents.Paragraph paragraph1 = section.AddParagraph();
                ShapeObject shape = paragraph1.AppendShape(240, 60, ShapeType.TextWave);

                //设置shape的位置
                shape.VerticalPosition = 80;
                shape.HorizontalPosition = 100;

                //写入艺术字文本和设置斜体
                shape.WordArt.Text = "艺术字效果";
                shape.WordArt.Italic = true;

                //设置文字填充样式
                shape.FillColor = System.Drawing.Color.Red;
                shape.StrokeColor = System.Drawing.Color.Gray;

                // Save the document and launch to see the output




                Spire.Doc.Documents.Paragraph paragraph2 = document.Sections[0].Paragraphs[2];
                Spire.Doc.Fields.Footnote footnote = paragraph2.AppendFootnote(FootnoteType.Footnote);
                DocumentObject obj = null;

                for (int i = 0; i < paragraph.ChildObjects.Count; i++)

                {

                    obj = paragraph.ChildObjects[i];

                    if (obj.DocumentObjectType == DocumentObjectType.TextRange)

                    {

                        TextRange textRange = obj as TextRange;

                        if (textRange.Text == "推箱子")

                        {

                            //为添加脚注的字符串设置加粗格式

                            textRange.CharacterFormat.Bold = true;

                            //插入脚注

                            paragraph.ChildObjects.Insert(i + 1, footnote);

                            break;

                        }

                    }

                }
                TextRange text = footnote.TextBody.AddParagraph().AppendText("推箱子是一款来自日本的古老游戏,其设计目的是训练人的逻辑思维能力。游戏场景一般是设定在空间狭小的仓库中,要求把箱子摆放到指定位置。这就要求玩家巧妙的运用有限的空间和通道,合理的安排箱子的位置和移动次序才可能完成任务。");

                text.CharacterFormat.FontName = "Arial Black";

                text.CharacterFormat.FontSize = 9;

                text.CharacterFormat.TextColor = Color.DarkGray;

                footnote.MarkerCharacterFormat.FontName = "Calibri";

                footnote.MarkerCharacterFormat.FontSize = 12;

                footnote.MarkerCharacterFormat.Bold = true;

                footnote.MarkerCharacterFormat.TextColor = Color.DarkGreen;




                document.SaveToFile("content.doc", FileFormat.Doc);
                //System.Diagnostics.Process.Start("text.docx");
            }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message);
            }
        }
    }
}

添加com引用

使用菜单:项目 -- 添加引用,在 COM 标签页添加名为 "MicrosoftWord 15.0 Object Library" Word 对象互操作库
在程序代码源文件中添加命名空间支持:
using MsWord=Microsoft.Office.Interop.Word;
所有操作 Word 对象的 COM 方法调用代码必须处在在异常处理代码块中,先创建 Word
Application 对象,它是 Word 对象操作的最开始,创建此对象时 WINWORD.EXE 进程启动。
MsWord.Application oWordApplic;//a reference to Wordapplication
MsWord.Document oDoc;//a reference to thedocument
try
{
}
catch (Exception e2)
{
MessageBox.Show(e2.Message);
}
后续所有操作 Word 对象的代码都要处于 Try 语法块中。

检测到旧的 word 档后删除旧文档。

string doc_file_name = Directory.GetCurrentDirectory() + @"\content.doc";
if (File.Exists(doc_file_name))
{
File.Delete(doc_file_name);
}
oWordApplic = new MsWord.Application();
object missing = System.Reflection.Missing.Value;

创建 Word 文档的小节

分节符在 Word 文档中是用来生成小节的控制符,每小节的页眉页脚的内容,页码格式等
保持一致。本项目生成的 Word 文档要求有不同的页码格式和页眉内容,首先插入 4 个分节符获得 5 个小节,第 1 小节是摘要内容,第 2 小节是目录,第 3 小节是第一章,第 4 小节是表 格,第 5 小节是图片。第 1, 2 小节的页码是大写罗马数字,第 3 4 5 小节的页码是阿拉伯 数字,且起始页码为 1

MsWord.Range curRange;
object curTxt;
int curSectionNum = 1;
oDoc = oWordApplic.Documents.Add(ref missing, ref missing, ref missing, ref missing);
oDoc.Activate();
Console.WriteLine(" 正在生成文档小节");
object section_nextPage = MsWord.WdBreakType.wdSectionBreakNextPage;
object page_break = MsWord.WdBreakType.wdPageBreak;
//添加三个分节符,共四个小节
for (int si = 0; si < 4; si++)
{
oDoc.Paragraphs[1].Range.InsertParagraphAfter();
oDoc.Paragraphs[1].Range.InsertBreak(ref section_nextPage);
 }


http://www.kler.cn/a/156980.html

相关文章:

  • [SWPUCTF 2022 新生赛]Power! 反序列化详细题解
  • Vue 中的定时刷新与自动更新实现
  • macos中安装和设置ninja
  • C++《stack与queue》
  • 【Vue】Vue3.0(二十)Vue 3.0 中mitt的使用示例
  • qt QFrame详解
  • Nacos与Eureka的区别
  • 【COCI2011-2012#5】 EKO / 砍树
  • Mybatis总结
  • C++11改进单例模式
  • CMMI认证有什么意义
  • GPIO的使用--操作PF09 PF10 PF08实现呼吸灯、跑马灯、警报闪烁灯
  • 开源CDN软件GoEdge —— 筑梦之路
  • 马斯克没继续的工作,我帮他继续下去
  • [蓝桥杯 2019 省 B] 特别数的和-C语言的解法
  • Anaconda和Python关系详解和使用选择
  • Educational Codeforces Round 159(div2) --- E. Collapsing Strings-- 题解
  • Redis数据库
  • 卷麻了,00后测试用例写的比我还好,简直无地自容......
  • spring日志输出到elasticsearch
  • 【有机化学(药学类)】醛和酮3
  • 刷题系列——排序算法
  • Python面向对象③:封装【侯小啾Python基础领航计划 系列(二十一)】
  • 5.【自动驾驶与机器人中的SLAM技术】2D点云的scan matching算法 和 检测退化场景的思路
  • Android之 知识总结第二篇
  • 用python写一个简单的爬虫