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")))));
}
}
}
}
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);
}
}
}
}
}
But in this case you should reference COM type library Microsoft. Word Object Library.
Here are very useful things about COM interop: How do I properly clean up Excel interop objects?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…