使用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);}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/224693.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

JavaScript 的初步学习上篇

JavaScript 的介绍 JavaScript 之父 布兰登 . 艾奇 (Brendan Eich) ,1995 年, 用 10 天时间完成 JavaScript 的设计. JavaScript 和 Java 的关系 两者之间就像老婆和老婆饼的关系,即毫无关系, JavaScript 最初的名字叫LiveScript,为了蹭 Java 热度,才改名为 JavaScript.JavaScr…

JVM——垃圾回收器(Serial,SerialOld,ParNew,CMS,Parallel Scavenge,Parallel Old)

目录 1.垃圾回收器的组合关系1.年轻代-Serial垃圾回收器2.老年代-SerialOld垃圾回收器3.年轻代-ParNew垃圾回收器4.老年代- CMS(Concurrent Mark Sweep)垃圾回收器CMS执行步骤&#xff1a;CMS垃圾回收器存在的问题缺点&#xff1a;CMS垃圾回收器存在的问题 – 线程资源争抢问题…

【Redis缓存】RedisTemplate如何获取符合要求的key,批量获取key

RedisTemplate如何获取符合要求的key,批量获取key 一、方法/命令二、数据使用 一、方法/命令 如果使用命令的形式&#xff0c;输入以下命令即可 keys *如果使用RedisTemplate&#xff0c;则方法为 redisTemplate.keys()获取所有符合条件的key。 二、数据使用 redis中缓存了…

动静分离+多实例实验(nginx+tomcat)

Nginx服务器&#xff1a;192.168.188.14:80 Tomcat服务器1&#xff1a;192.168.188.11:80 Tomcat服务器2&#xff1a;192.168.188.12:8080 192.168.188.12:8081 部署Nginx负载均衡器 关闭防火墙 systemctl stop firewalld setenforce 0 安装依赖 yum -y install pcre-dev…

自研分布式IM-HubuIM RFC草案

HubuIM RFC草案 消息协议设计 基本协议 评估标准 【性能】协议传输效率&#xff0c;尽可能降低端到端的延迟&#xff0c;延迟高于200ms用户侧就会有所感知 【兼容】既要向前兼容也要向后兼容 【存储】减少消息包的大小&#xff0c;降低空间占用率&#xff0c;一个字节在亿…

抖音本地生活服务商申请要多久审核通过?

近年来&#xff0c;随着互联网的普及和社交媒体的兴起&#xff0c;本地生活服务行业也迎来了巨大的发展机遇。作为最受欢迎的短视频平台之一&#xff0c;抖音也不例外。抖音本地生活服务商申请要多久审核通过&#xff1f;这是许多想要加入抖音本地服务行业的人们最关心的问题之…

paddleocr笔记

PP-OCRv1 PP-OCR中&#xff0c;对于一张图像&#xff0c;需要完成以下3个步骤提取其中的文字信息&#xff1a; 使用文本检测方法&#xff0c;获取文本区域多边形信息&#xff08;PP-OCR中文本检测使用的是DBNet&#xff0c;因此获取的是四点信息&#xff09;。对上述文本多边形…

Echarts-使用渐变色填充

垂直方向的渐变 color: {type: linear,// x0,y1,柱子的颜色在垂直方向渐变x: 0,y: 1,colorStops: [// 0%处的颜色{offset: 0,color: #12c2e9,},// 50%处的颜色{offset: 0.5,color: #c471ed,},// 100%处的颜色{offset: 1,color: #f64f59,},],global: false // 缺省为 false} 水…

11.25快速排序细节,sort函数,二分使面积差最小

快速排序 i从左边开始&#xff0c;遇到大于等于x的停下来&#xff0c;j遇到小于等于x的停下来&#xff0c;然后如果i<j&#xff0c;就交换。 递归可能有两种写法&#xff0c;即开始&#xff0c;左-1&#xff0c;左&#xff0c;结束 与开始&#xff0c;右&#xff0c;右1&a…

FLASK博客系列5——模板之从天而降

我们啰啰嗦嗦讲了4篇&#xff0c;都是在调接口&#xff0c;啥时候能看到漂亮的页面呢&#xff1f;别急&#xff0c;今天我们就来实现。 来我们先来实现一个简单的页面。不多说&#xff0c;上代码。 app.route(/) def index():user {username: clannadhh}return <html>&…

【探索Linux】—— 强大的命令行工具 P.17(进程信号 —— 信号保存 | 阻塞信号 | sigprocmask() | sigpending() )

阅读导航 引言一、阻塞信号1. 信号相关常见概念&#xff08;1&#xff09;信号递达&#xff08;2&#xff09;信号未决&#xff08;3&#xff09;阻塞信号&#xff08;4&#xff09;忽略信号 2. 信号在内核中的表示⭕信号在内核中的表示示意图 3. sigset_t &#xff08;数据类型…

用于图像分类任务的经典神经网络综述

&#x1f380;个人主页&#xff1a; https://zhangxiaoshu.blog.csdn.net &#x1f4e2;欢迎大家&#xff1a;关注&#x1f50d;点赞&#x1f44d;评论&#x1f4dd;收藏⭐️&#xff0c;如有错误敬请指正! &#x1f495;未来很长&#xff0c;值得我们全力奔赴更美好的生活&…