12
2020
07

Spire.doc对word的操作总结

Word操作汇总
 
1、         打开已有word文件,这是要处理word文件的最基本也是必须的步骤。他提供了三种方法。
 
方法1:从已知特定的文档中初始化一个新的Document 类的实例
 
Document document = new Document(@"..\..\Sample.docx"); 

方法2、从文件中加载一个word文件
 
Document document = new Document();
document.LoadFromFile(@"..\..\Sample.docx");
 
方法3、从流文件中加载word文件
 
Stream stream = File.OpenRead(@"..\..\Sample.docx");
Document document = new Document(stream);
 
2、如何创建表格
 
Document document = new Document();
Section section = document.AddSection();
 
Table table = section.AddTable(true);
table.ResetCells(2, 3);
 
TableRow row = table.Rows[0];
row.IsHeader = true;
 
Paragraph para = row.Cells[0].AddParagraph();
TextRange TR = para.AppendText("Item");
 
para = row.Cells[1].AddParagraph();
TR = para.AppendText("Description");
 
para = row.Cells[2].AddParagraph();
TR = para.AppendText("Qty");
 
document.SaveToFile("WordTable.docx");
 
System.Diagnostics.Process.Start("WordTable.docx");
 
 
我们还可以设置行高和列宽
 
3、如何插入超链接?你可以插入两种超链接,Email 链接和webmail 链接。   
 
Documentdocument =newDocument();
Section section = document.AddSection();
 
//Insert URL hyperlink
Paragraph paragraph = section.AddParagraph();
paragraph.AppendText("Home page");
paragraph.ApplyStyle(BuiltinStyle.Heading2);
paragraph = section.AddParagraph();
paragraph.AppendHyperlink("www.e-iceblue.com", "www.e-iceblue.com",HyperlinkType.WebLink);
 
//Insert email address hyperlink
paragraph = section.AddParagraph();
paragraph.AppendText("Contact US");
paragraph.ApplyStyle(BuiltinStyle.Heading2);
paragraph = section.AddParagraph();
paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "support@e-iceblue.com",HyperlinkType.EMailLink);
 
document.SaveToFile("Hyperlink.docx");
System.Diagnostics.Process.Start("Hyperlink.docx");
 
 

4、如何加入注解
 
Document document = new Document();
Section section = document.AddSection();
 
Paragraph paragraph = section.AddParagraph();
paragraph.AppendText("Home Page of ");
TextRange textRange = paragraph.AppendText("e-iceblue");
 
Comment comment1 = paragraph.AppendComment("www.e-iceblue.com");
comment1.AddItem(textRange);
comment1.Format.Author = "Harry Hu";
comment1.Format.Initial = "HH";
 
document.SaveToFile("Comment.docx");
System.Diagnostics.Process.Start("Comment.docx");
 
 
5、如何加入书签
 
Document document = new Document();
Section section = document.AddSection();
 
Paragraph paragraph = section.AddParagraph();
 
paragraph.AppendBookmarkStart("SimpleBookMark");
paragraph.AppendText("This is a simple book mark.");
paragraph.AppendBookmarkEnd("SimpleBookMark");
 
document.SaveToFile("Bookmark.docx");
System.Diagnostics.Process.Start("Bookmark.docx");
 
 
6、合并邮件
 
Document document = new Document();
document.LoadFromFile("Fax.doc");
 
string[] filedNames = new string[] { "Contact Name", "Fax", "Date" };
 
string[] filedValues = new string[] { "John Smith", "+1 (69) 123456", System.DateTime.Now.Date.ToString() };
 
document.MailMerge.Execute(filedNames, filedValues);
 
document.SaveToFile("MailMerge.doc", FileFormat.Doc);
System.Diagnostics.Process.Start("MailMerge.doc");
 
  
7、加入表单,这部分包含创建以及填入表单域。
 
创建表单
//Add new section to document
Section section = document.AddSection();
 
//Add Form to section
private void AddForm(Section section)
 
//add text input field
TextFormField field
= fieldParagraph.AppendField(fieldId, FieldType.FieldFormTextInput) as TextFormField;
 
//add dropdown field
DropDownFormField list
= fieldParagraph.AppendField(fieldId, FieldType.FieldFormDropDown) as DropDownFormField;
 
//add checkbox field
fieldParagraph.AppendField(fieldId, FieldType.FieldFormCheckBox);
 
 
填入表单域
 
//Fill data from XML file
using (Stream stream = File.OpenRead(@"..\..\..\Data\User.xml"))
{
    XPathDocument xpathDoc = new XPathDocument(stream);
XPathNavigator user = xpathDoc.CreateNavigator().SelectSingleNode("/user");
 
Fill data:
 
foreach (FormField field in document.Sections[0].Body.FormFields)
  {
     String path = String.Format("{0}/text()", field.Name);
     XPathNavigator propertyNode = user.SelectSingleNode(path);
     if (propertyNode != null)
     {
         switch (field.Type)
         {
             case FieldType.FieldFormTextInput:
                  field.Text = propertyNode.Value;
                  break;
 
             case FieldType.FieldFormDropDown:
                  DropDownFormField combox = field as DropDownFormField;
                  for(int i = 0; i < combox.DropDownItems.Count; i++)
                  {
                      if (combox.DropDownItems[i].Text == propertyNode.Value)
                      {
                         combox.DropDownSelectedIndex = i;
                         break;
                      }
                      if (field.Name == "country" && combox.DropDownItems[i].Text =="Others")
                      {
                         combox.DropDownSelectedIndex = i;
                      }
                  }
                  break;
 
             case FieldType.FieldFormCheckBox:
                  if (Convert.ToBoolean(propertyNode.Value))
                  {
                      CheckBoxFormField checkBox = field as CheckBoxFormField;
                      checkBox.Checked = true;
                  }
                  break;
            }
       }
   }
 }
 
  
8、合并word文档
 
//Load two documents
//Load Document1 and Document2
Document DocOne = new Document();
DocOne.LoadFromFile(@"E:\Work\Document\welcome.docx", FileFormat.Docx);
Document DocTwo = new Document();
DocTwo.LoadFromFile(@"E:\Work\Document\New Zealand.docx", FileFormat.Docx);
 
//Merge
foreach (Section sec in DocTwo.Sections)
{
 DocOne.Sections.Add(sec.Clone());
}
//Save and Launch
DocOne.SaveToFile("Merge.docx", FileFormat.Docx);
 
9、保护文档。你可以设置密码或者加入水印来进行保护。文字和图片的水印都支持。

//Protect with password
document.Encrypt("eiceblue");
 
//Add Text watermark:
TextWatermark txtWatermark = new TextWatermark();
txtWatermark.Text = "Microsoft";
txtWatermark.FontSize = 90;
txtWatermark.Layout = WatermarkLayout.Diagonal;
document.Watermark = txtWatermark;
 
//Add Image watermark:
PictureWatermark picture = new PictureWatermark();
picture.Picture = System.Drawing.Image.FromFile(@"..\imagess.jpeg");
picture.Scaling = 250;
document.Watermark = picture;
 
10、转换功能是在处理word文档时最常见的操作了。使用免费版的Spire.doc  for .NET, 转换变得很简单。只要包含三行类似的代码你就可以把word转换成其他常用格式,像PDF,HTML和图片。
Word转换成PDF
 
SaveToFile("Target PDF.PDF", FileFormat.PDF);
 
Word转换成图片
 
Image image = document.SaveToImages(0, ImageType.Bitmap);
image.Save("Sample.tiff", ImageFormat.Tiff);
 
Word转换成HTML
 
document.SaveToFile("Target HTML.html", FileFormat.Html);
WordDocViewer(""Target HTML.html");
 
结论:
这是一个免费又强大的C# word 组件,它不需要 Word automatio即可运行,并且任何第三方的功能都囊括。


12
2020
07

sprie pdf 导出前几页

C# 将一个 PDF 页面拆分为多页

//加载PDF文档
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("New Zealand.pdf");

//获取第一页
PdfPageBase page = pdf.Pages[0];

//创建新PDF文档
PdfDocument newPdf = new PdfDocument();

//移除新文档的页边距
newPdf.PageSettings.Margins.All = 0;

//设置新文档页面的宽度等于原文档第一页的宽度,页面高度等于原文档第一页高度的一半
newPdf.PageSettings.Width = page.Size.Width;
newPdf.PageSettings.Height = page.Size.Height / 2;

//添加新页面到新文档
PdfPageBase newPage = newPdf.Pages.Add();

PdfTextLayout format = new PdfTextLayout();
format.Break = PdfLayoutBreakType.FitPage;
format.Layout = PdfLayoutType.Paginate;

//根据原文档第一页创建模板,并将模板画到新文档的新添加页面,页面画满之后自动分页
page.CreateTemplate().Draw(newPage, new PointF(0, 0), format);

//保存
newPdf.SaveToFile("HorizontallySplit.pdf");

newPdf.Close();
pdf.Close();

纵向拆分

12
2020
07

Word按页读取内容

/// <summary>
        /// Word按页读取内容
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="isHtml">html或纯文本</param>
        /// <returns></returns>
        /// 
        public string ReadPage(int page, bool isHtml)
        {
            object objWhat = Word.WdGoToItem.wdGoToPage;
            object objWhich = Word.WdGoToDirection.wdGoToAbsolute;

            object objPage = page;
            Word.Range range1 = oDoc.GoTo(ref objWhat, ref objWhich, ref objPage, ref missing);
            Word.Range range2 = range1.GoToNext(Word.WdGoToItem.wdGoToPage);

            object objStart = range1.Start;
            object objEnd = range2.Start ;
            if (range1.Start == range2.Start)
                objEnd = oDoc.Characters.Count;//最后一页
            oDoc.Range(ref objStart, ref objEnd).Copy();

            if (isHtml)
            {
                MemoryStream stream =   Clipboard.GetData("Html Format") as MemoryStream;
                stream.Position = 0;//解决从剪切板复制中文内容乱码的问题www.xuehi.com
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, (int)stream.Length);

                return Encoding.UTF8.GetString(bytes);
            }
            else
            {
                byte[] bytes = Encoding.Default.GetBytes((string)Clipboard.GetData(DataFormats.Text));

                return Encoding.GetEncoding("gb2312").GetString(bytes);
            }
        }


12
2020
07

C#获取Word文档操作

using MSWord = Microsoft.Office.Interop.Word;  

MSWord.Application wordApp; //Word应用程序变量

MSWord.Document wordDoc;    //Word文档变量

Object Nothing = Missing.Value;  //初始化

wordApp = new MSWord.ApplicationClass();

wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, refNothing, ref Nothing); // 新建Word

 

// 打开已存在的Word

object FileName = strPath;

object readOnly = false;

object isVisible = true;

wordDoc = wordApp.Documents.Open(ref FileName, ref Nothing, refreadOnly, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, refNothing, ref Nothing, ref Nothing, ref isVisible, ref Nothing, ref Nothing, refNothing, ref Nothing);  



// 计算Word文档页数

MSWord.WdStatistic stat = MSWord.WdStatistic.wdStatisticPages;

int num = wordDoc.ComputeStatistics(stat, ref  Nothing);



// 跳转到指定书签

object what = MSWord.WdGoToItem.wdGoToBookmark;

object BookMarkName = "BookMark1";

wordDoc.ActiveWindow.Selection.GoTo(ref what, ref Nothing, refNothing, ref BookMarkName);

MessageBox.Show(wordDoc.ActiveWindow.Selection.Paragraphs[1].Range.Text.ToString()); 



//跳转到指定页

object What = MSWord.WdGoToItem.wdGoToPage;

object Which = MSWord.WdGoToDirection.wdGoToNext;

object Name = "1"; // 页数

wordDoc.ActiveWindow.Selection.GoTo(ref What, ref Which, refNothing, ref Name); // 第二个参数可以用Nothing

MessageBox.Show(wordDoc.ActiveWindow.Selection.Paragraphs[1].Range.Text.ToString()); 

MessageBox.Show(wordDoc.ActiveWindow.Selection.Sentences[1].Text.ToString());

MessageBox.Show(wordDoc.ActiveWindow.Selection.Paragraphs[1].Range.Sentences[1].Text.ToString());



MessageBox.Show(wordDoc.Content.Paragraphs[8].Range.Text.ToString());
MessageBox.Show(wordDoc.Content.Paragraphs[8].Range.Sentences[1].Text.ToString());





//插入段落并分页

Word.Paragraph oPara4;
oPara4 = mydoc.Content.Paragraphs.Add(ref oMissing);
oPara4.Range.Text = "附图一:";
oPara4.Range.Font.Name = "宋体";
oPara4.Range.Font.Size = 10.5f; 
oPara4.Range.InsertParagraphAfter();
insertChart(saveDocPath);//插入excel-chart
oPara4.Range.InsertParagraphAfter();


//插入分页符
insertBreakNextPage();



//用正则表达式分割段落

string string2 = "  段落1。\r\n 段落2。\r\n 段落3。";
string[] Paras = System.Text.RegularExpressions.Regex.Split(string2, @"\r\n");



//插入回车符

word.Selection.TypeParagraph();

//插入回格符

word.Selection.TypeBackspace();

//跳转到文档结尾

object wd_story = Word.WdUnits.wdStory;

word.Selection.EndKey(ref wd_story, ref oMissing);


04
2020
07

vsto 开发office 集合

vsto下开发wps插件

https://www.cnblogs.com/wangqiang3311/p/8134072.html


WPS插件开发流程(1)

https://blog.csdn.net/wenjian005/article/details/80161633


WPS插件开发流程(2)

https://blog.csdn.net/wenjian005/article/details/80248185


c#开发wps插件

https://www.cnblogs.com/wangqiang3311/p/7205416.html


c#开发wps插件(2)

https://www.cnblogs.com/wangqiang3311/p/7206105.html


wpsAddin示例代码

https://github.com/wangqiang3311/wpsAddin


c#开发wps插件(3)部署

https://www.cnblogs.com/wangqiang3311/p/7206406.html


02
2020
07

wps 转 pdf C# 实现

项目需求:不打算用office自带的组件实现word转pdf操作

环境需求:安装wps2016专业版

30
2020
06

C#开发之Word批量转PDF

C#开发之Word批量转PDF

源码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using Microsoft.Office.Interop.Word;
 
namespace Word2Pdf
{
    class Program
    {
        public static Microsoft.Office.Interop.Word.Document wordDocument { get; set; }
 
        static void Main(string[] args)
        {
            string strFolder_f = null;
            string strFolder_t = null;
            string strFlag = null;
            System.Console.WriteLine("请输入Word文档所在目录");
            strFolder_f = System.Console.ReadLine();
            if (strFolder_f.Substring(strFolder_f.Length - 1, 1) != "\\")
            {
                strFolder_f += "\\";
            }
            strFolder_t = strFolder_f + @"pdf\";
            System.Console.WriteLine("\n创建PDF文档,请确认!");
            System.Console.Write("y(yes) or n(no) ?  ");
            strFlag = System.Console.ReadLine();
            if (strFlag == "y")
            {
                System.Console.WriteLine("\n开始创建PDF文档...");
                CheckFolder(strFolder_t);
                string strPdfFile = null;
                DirectoryInfo TheFolder = new DirectoryInfo(strFolder_f);
 
                Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
                object paramMissing = Type.Missing;
 
                foreach (FileInfo NextFile in TheFolder.GetFiles())
                {
                    strPdfFile = Path.ChangeExtension(strFolder_t + NextFile.Name, ".pdf");
                    wordDocument = appWord.Documents.Open(NextFile.FullName);
                    if (wordDocument != null)
                    {
                        wordDocument.ExportAsFixedFormat(strPdfFile, WdExportFormat.wdExportFormatPDF);
                        wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                        wordDocument = null;
                    }
                    System.Console.Write(".. ");
                }
 
                if (appWord != null)
                {
                    appWord.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    appWord = null;
                }
            }
 
            //KillProcessByName("WINWORD");
            GC.Collect();
            GC.WaitForPendingFinalizers();
 
            System.Console.Write("\n处理完毕,输入任意键退出");
            System.Console.ReadKey();
        }
 
        static void CheckFolder(string strFolderPath)
        {
            if (Directory.Exists(strFolderPath))
            {
                Directory.Delete(strFolderPath, true);
                Directory.CreateDirectory(strFolderPath);
            }
            else
            {
                Directory.CreateDirectory(strFolderPath);
            }
        }
 
        static void KillProcessByName(string name)
        {
            Process[] ps = Process.GetProcessesByName(name);
            foreach (Process p in ps)
            {
                if (p.ProcessName == name)
                    p.Kill();
            }
        }
    }
}


30
2020
06

wps 转 pdf 代码

using System;
using System.IO;
using Word;
namespace WpsToPdf
{
    class Wps2Pdf : IDisposable
    {
        dynamic wps;
        public Wps2Pdf()
        {
             //这里创建wps实例不知道用了什么骚操作就没有报错过 本机安装的是wps2016
            Type type = Type.GetTypeFromProgID("KWps.Application");
            wps = Activator.CreateInstance(type);
        }
        public void ToPdf(string wpsFilename, string pdfFilename = null)
        {
            if (wpsFilename == null) { throw new ArgumentNullException("wpsFilename"); }
            if (pdfFilename == null)
            {
                pdfFilename = Path.ChangeExtension(wpsFilename, "pdf");
            }
            Console.WriteLine(string.Format(@"正在转换 [{0}]
      -> [{1}]", wpsFilename, pdfFilename));
             //到处都是dynamic   看的我一脸懵逼
            dynamic doc = wps.Documents.Open(wpsFilename, Visible: false);//这句大概是用wps 打开  word  不显示界面
            doc.ExportAsFixedFormat(pdfFilename, WdExportFormat.wdExportFormatPDF);//doc  转pdf 
            doc.Close();
        }
        public void Dispose()
        {
            if (wps != null) { wps.Quit(); }
        }
    }
}


09
2019
01

c# word 操作系列之C# 根据Word模版生成Word文件

添加com Microsoft word 11.0 Object Library 引用

09
2019
01

c# word 操作系列之Word代码实现

参考资料:

http://www.cnblogs.com/wngwz/archive/2004/08/19/34678.html

https://www.cnblogs.com/xh6300/p/5915717.html