你是否正在寻找.NET Word自动化解决方案 以在C#中生成和处理文字处理文档?让我们尝试一下Aspose.Words for .NET API。

让我们尝试一下Aspose.Words for .NET API- 在基于.NET或.NET Core的应用程序中用于生成和处理Word文档(.doc,.docx等)的完整功能集。通过接下来的介绍,你将了解到:

  • 创建一个Word(.doc,.docx)文档。
  • 将Word文档转换为其他格式,例如PDF。
  • 解析Word文档。

如果你还没有用过Aspose.Words可以点击这里下载最新版测试。


①使用C#动态创建Word文档

DocumentBuilder类包含从头创建Word文档的所有方法和属性。与Document类结合使用时,DocumentBuilder支持插入元素,例如文本/段落,复选框,表格,列表,图像以及Word文档可以包含的其他对象。此外,您可以使用此类指定字体和其他格式选项。以下是使用DocumentBuilder类创建Word文档的步骤。

  • 创建一个新的Document对象。
  • 创建一个新的DocumentBuilder对象,并使用Document对象对其进行初始化
  • 使用DocumentBuilder对象插入/写入元素
  • 使用Document.Save方法保存文档

下面的代码示例演示如何使用C#格式的文本,表格和图像创建Word DOCX文档。

Document doc = new Document();DocumentBuilder builder = new DocumentBuilder(doc);// Specify font formattingFont font = builder.Font;font.Size = 32;font.Bold = true;font.Color = System.Drawing.Color.Black;font.Name = "Arial";font.Underline = Underline.Single;// Insert textbuilder.Writeln("This is the first page.");builder.Writeln();// Change formatting for next elements.font.Underline = Underline.None;font.Size = 10;font.Color = System.Drawing.Color.Blue;builder.Writeln("This following is a table");// Insert a tableTable table = builder.StartTable();// Insert a cellbuilder.InsertCell();// Use fixed column widths.table.AutoFit(AutoFitBehavior.AutoFitToContents);builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;builder.Write("This is row 1 cell 1");// Insert a cellbuilder.InsertCell();builder.Write("This is row 1 cell 2");builder.EndRow();builder.InsertCell();builder.Write("This is row 2 cell 1");builder.InsertCell();builder.Write("This is row 2 cell 2");builder.EndRow();builder.EndTable();builder.Writeln();// Insert imagebuilder.InsertImage("image.png");// Insert page breakbuilder.InsertBreak(BreakType.PageBreak);     // all the elements after page break will be inserted to next page.// Save the documentdoc.Save("Document.docx");

效果展示:

// Load documentDocument doc = new Document("Document.docx");DocumentBuilder builder = new DocumentBuilder(doc);// Access the paragraphvar paragraph=doc.Sections[0].Body.Paragraphs[0].Runs[0];paragraph.Text = "This is updated text"; // Save the documentdoc.Save("Document_updated.docx");

更新后效果:

③将Word文档转换为C#的其他格式

除了创建和处理Word文档外,Aspose.Words for .NET还允许将文档转换为其他格式,包括(但不限于)PDF,XPS,EPUB,HTML和图像格式,例如BMP,PNG或JPEG。下面的代码示例演示如何在C#中将Word文档转换为PDF。

Document doc = new Document("word.docx");// Provide PDFSaveOption compliance to PDF17PdfSaveOptions options = new PdfSaveOptions();options.Compliance = PdfCompliance.Pdf17;// Convert Word to PDFdoc.Save("output.pdf", options);

④用C#解析Word文档

通过将Word文档的内容提取为纯文本来解析Word文档。下面的代码示例演示如何从Word文档中提取文本并将其保存到.txt文件中。

// Load the document from disk.Document doc = new Document("document.docx");// Save as plain textdoc.Save("output.txt");

还想要更多吗可以点击阅读【2019 · Aspose最新资源整合】查找需要的教程资源。如果您有任何疑问或需求,请随时联系客服,我们很高兴为您提供查询和咨询

标签:

声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

上一篇 2020年1月6日
下一篇 2020年1月6日

相关推荐

发表回复

登录后才能评论