Evg*_*nko 18
安装OpenXML SDK后,您将能够引用DocumentFormat.OpenXml
程序集: Add Reference
- > Assemblies
- >
Extensions
- > DocumentFormat.OpenXml
.您还需要参考WindowsBase
.
比你能够生成文档,例如,像这样:
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")))));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用Productivity Tool(相同的链接)从文档生成代码.它有助于了解如何使用SDK API.
您可以使用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);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,您应该引用COM类型库Microsoft.Word对象库.
以下是关于COM互操作的非常有用的东西:如何正确清理Excel互操作对象?
归档时间: |
|
查看次数: |
22672 次 |
最近记录: |