Ответ 1
После установки 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")))));
}
}
}
}
Также вы можете использовать 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);
}
}
}
}
}
Но в этом случае вам следует обратиться к библиотеке COM-типа Microsoft. Библиотека объектов Word.
Вот очень полезные вещи о COM-взаимодействии: Как правильно очистить объекты взаимодействия Excel?