我如何创建的Microsoft.Office.Interop.Word中的.docx文件? [英] How do I create the .docx document with Microsoft.Office.Interop.Word?
问题描述
我如何创建的Microsoft.Office.Interop.Word从列表中的.docx文件?或者最好的办法是增加docx.dll?
How do I create the .docx document with Microsoft.Office.Interop.Word from List? or the best way is to add docx.dll?
<一个href="http://www.c-sharpcorner.com/UploadFile/scottlysle/using-the-docx-dll-to-programmatically-create-word-documents/">http://www.c-sharpcorner.com/UploadFile/scottlysle/using-the-docx-dll-to-programmatically-create-word-documents/
更新。的可能是我的第一个问题就是痘痘不正确。的Microsoft.Office.Interop.Word和DocX.dll之间的区别是什么?我是否需要Microsft词在这两种情况下创建和打开的.docx文件?
Update. May be my first question is a litle incorrect. What is the difference between Microsoft.Office.Interop.Word and DocX.dll? Do I need Microsft Word for creating and opening .docx document in both cases?
推荐答案
安装的OpenXML后SDK 你将能够引用 DocumentFormat.OpenXml
组件:添加引用
- > 组件
- >
扩展
- > DocumentFormat.OpenXml
。此外,您将需要引用 WindowsBase
。
After installing OpenXML SDK you will able to reference DocumentFormat.OpenXml
assembly: Add Reference
-> Assemblies
->
Extensions
-> DocumentFormat.OpenXml
. Also you will need to reference WindowsBase
.
比您将能够生成文档,例如,像这样的:
Than you will be able to generate document, for example, like this:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace MyNamespace
{
class Program
{
static void Main(string[] args)
{
using (var document = WordprocessingDocument.Create(
"test.docx", WordprocessingDocumentType.Document))
{
document.AddMainDocumentPart();
document.MainDocumentPart.Document = new Document(
new Body(new Paragraph(new Run(new Text("some text")))));
}
}
}
}
你也可以使用生产力工具(同一个链接)来生成文件code。它可以帮助了解如何使用SDK API的工作。
Also you can use Productivity Tool (the same link) to generate code from document. It can help to understand how work with SDK API.
您可以使用互操作做同样的:
You can do the same with Interop:
using System.Reflection;
using Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
namespace Interop1
{
class Program
{
static void Main(string[] args)
{
Application application = null;
try
{
application = new Application();
var document = application.Documents.Add();
var paragraph = document.Paragraphs.Add();
paragraph.Range.Text = "some text";
string filename = GetFullName();
application.ActiveDocument.SaveAs(filename, WdSaveFormat.wdFormatDocument);
document.Close();
}
finally
{
if (application != null)
{
application.Quit();
Marshal.FinalReleaseComObject(application);
}
}
}
}
}
但在这种情况下,你应该引用COM类型库微软。 Word对象库。
But in this case you should reference COM type library Microsoft. Word Object Library.
下面是关于COM互操作非常有用的东西:如何正确清洁最多的Excel互操作对象
Here are very useful things about COM interop: How to properly clean up Excel interop objects
这篇关于我如何创建的Microsoft.Office.Interop.Word中的.docx文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!