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

使用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 Wordapplicationpublic static MsWord.Document oDoc;//a reference to thedocumentpublic 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;//起如页码为 1common.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 footerSpire.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 imageparagraph.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 outputSpire.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);}

相关文章:

  • 【每日易题】Leetcode上Hard难度的动态规划题目——地下城游戏的实现
  • Android wifi 框架以及Enable流程
  • 第八节HarmonyOS @Component自定义组件的生命周期
  • ubuntu虚拟机设置跳不出来
  • 【Rust】所有权的认识
  • 华为 ArkTS 边框怎么设置,当边边框怎么设置(鸿蒙开发)
  • 模拟电路学习笔记(一)之芯片篇(持续更新)
  • postgreSQL 查询所有模式的语句
  • 2023年JetBrains开发调查:Java 8仍广泛使用
  • MyBatis查询优化:枚举在条件构建中的妙用
  • OA系统是什么,能用低代码开发吗?
  • 外包干了2个月,技术明显退步了...
  • Sequential Modeling Enables Scalable Learning for Large Vision Models
  • Spring Security 6.x 系列(7)—— 源码分析之Builder设计模式
  • RK3568平台开发系列讲解(Linux系统篇)device_node 转换成 platform_device
  • C语言笔记(第一章:C语言编程)
  • JAVA 学习IO流
  • JAVA并发编程--1.基础概念
  • Leetcode 27 Remove Element
  • Python 基础起步 (十) 什么叫函数?
  • python学习笔记 - ThreadLocal
  • react-core-image-upload 一款轻量级图片上传裁剪插件
  • vue从入门到进阶:计算属性computed与侦听器watch(三)
  • 搭建gitbook 和 访问权限认证
  • 大主子表关联的性能优化方法
  • 关于Flux,Vuex,Redux的思考
  • 极限编程 (Extreme Programming) - 发布计划 (Release Planning)
  • 悄悄地说一个bug
  • 思否第一天
  • 学习笔记:对象,原型和继承(1)
  • 做一名精致的JavaScripter 01:JavaScript简介
  • AI又要和人类“对打”,Deepmind宣布《星战Ⅱ》即将开始 ...
  • ​一、什么是射频识别?二、射频识别系统组成及工作原理三、射频识别系统分类四、RFID与物联网​
  • #[Composer学习笔记]Part1:安装composer并通过composer创建一个项目
  • ()、[]、{}、(())、[[]]等各种括号的使用
  • (3)Dubbo启动时qos-server can not bind localhost22222错误解决
  • (day6) 319. 灯泡开关
  • (Matalb回归预测)PSO-BP粒子群算法优化BP神经网络的多维回归预测
  • (NO.00004)iOS实现打砖块游戏(十二):伸缩自如,我是如意金箍棒(上)!
  • (机器学习的矩阵)(向量、矩阵与多元线性回归)
  • (算法设计与分析)第一章算法概述-习题
  • .bat批处理(八):各种形式的变量%0、%i、%%i、var、%var%、!var!的含义和区别
  • .NET CF命令行调试器MDbg入门(二) 设备模拟器
  • .NET CF命令行调试器MDbg入门(三) 进程控制
  • .net mvc actionresult 返回字符串_.NET架构师知识普及
  • .net oracle 连接超时_Mysql连接数据库异常汇总【必收藏】
  • .NET6 命令行启动及发布单个Exe文件
  • @FeignClient注解,fallback和fallbackFactory
  • @RequestBody与@ResponseBody的使用
  • @Validated和@Valid校验参数区别
  • [Angular 基础] - 指令(directives)
  • [BZOJ4566][HAOI2016]找相同字符(SAM)
  • [C#]C# winform部署yolov8目标检测的openvino模型
  • [C++]AVL树怎么转
  • [C++]高精度 bign (重载运算符版本)