Nach OpenXML SDK Installation können Sie DocumentFormat.OpenXml
Assembly verweisen: Add Reference
->Assemblies
-> Extensions
->DocumentFormat.OpenXml
. Außerdem müssen Sie auf WindowsBase
verweisen.
als Sie in der Lage sein wird, Dokument zu erzeugen, zum Beispiel wie folgt aus:
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")))));
}
}
}
}
Sie können auch Productivity Tool (das gleiche Link) verwenden, um Code aus dem Dokument zu erzeugen. Es kann helfen zu verstehen, wie mit der SDK-API gearbeitet wird.
Sie können das gleiche mit Interop tun:
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);
}
}
}
}
}
Aber in diesem Fall sollten Sie COM-Typbibliothek Microsoft verweisen. Word-Objektbibliothek.
Hier sind sehr nützliche Dinge über COM-Interop: How do I properly clean up Excel interop objects?
Interop.Word erfordert, dass Office auf dem Computer installiert wird. DocX nicht, es hackt den OpenXML-Inhalt einer .docx-Datei direkt. Die übliche Wahl ist das Open XML SDK. Langfristige Unterstützung für diese Bibliothek würde normalerweise etwas beunruhigen. Überprüfen Sie die Problemliste auf bekannte Probleme. –