Как создавать word файл на c

В этом примере показано, как заставить C# создать документ Word. Сначала откройте диалоговое окно «Добавить ссылки». На вкладке COM выберите «Библиотека объектов Microsoft Word 14.0» (или любую другую версию, установленную в вашей системе).

Добавьте следующий с помощью оператора, чтобы упростить работу с пространством имен Word. Часть Word = означает, что вы можете использовать Word как псевдоним для пространства имен.

using Word = Microsoft.Office.Interop.Word;

В этом примере используется следующий код для создания нового документа Word и добавления в него текста.

 // Создаем документ Word.
private void btnGo_Click (отправитель объекта, EventArgs e)
{
// Получить объект приложения Word.
Word._Application word_app = new Word.ApplicationClass ();

// Сделать Word видимым (необязательно).
word_app.Visible = true;

// Создаем документ Word.
object missing = Type.Missing;
Word._Document word_doc = word_app.Documents.Add (
ref missing, ref missing, ref missing, ref missing);

// Создаем абзац заголовка.
Word.Paragraph para = word_doc.Paragraphs.Add (ref missing);
para.Range.Text = "Кривая хризантемы";
object style_name = "Заголовок 1";
para.Range.set_Style (ref style_name);
para.Range.InsertParagraphAfter ();

// Добавить текст.
para.Range.Text = «Сделать кривую хризантемы» +
«используйте следующие параметрические уравнения, когда t идет» +
"от 0 до 21 *? для генерации" +
«точки, а затем соединить их»;
para.Range.InsertParagraphAfter ();

// Сохраним текущий шрифт и начнем с использования Courier New.
string old_font = para.Range.Font.Name;
para.Range.Font.Name = "Courier New";

// Добавим уравнения.
para.Range.Text =
"r = 5 * (1 + Sin (11 * t / 5)) - n" +
«4 * Sin (17 * t / 3) ^ 4 * n" +
«Sin (2 * Cos (3 * t) - 28 * t) ^ 8 n" +
"x = r * Cos (t) n" +
"y = r * Sin (t)";

// Начнем новый абзац, а затем
// вернемся к исходному шрифту.
para.Range.InsertParagraphAfter ();
para.Range.Font.Name = old_font;

// Сохраним документ.
object filename = Path.GetFullPath (
Path.Combine (Application.StartupPath, ".. \ ..")) +
"\ test.doc";
word_doc.SaveAs(ref filename, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing);

// Закрыть.
object save_changes = false;
word_doc.Close (ref save_changes, ref missing, ref missing);
word_app.Quit (ref save_changes, ref missing, ref missing);
}

В этом примере видится сервер Word. В реальном приложении вы можете захотеть сохранить его скрытым.

Объектная модель Word использует множество вызовов методов, которые по какой-то причине принимают множество параметров по ссылке, даже если они не изменяются методами. Это означает, что вы должны поместить значения для этих параметров в переменные. Например, вы не можете использовать true как логический параметр, потому что вы не можете передавать константу по ссылке. Аналогично, вы не можете использовать литеральную строку, такую как C: wherever test.doc для имени файла, который вы открываете, потому что это не назначаемая переменная.

Код создает специальную переменную с именем missing, которая имеет значение Type.Missing. Код может использовать это значение для любых необязательных параметров, которые ему не нужно передавать методам Word. Затем программа использует его при вызове вызова Documents.Add сервера Word, который создает новый документ Word.

Теперь программа начинает добавлять текст в документ. Он добавляет объект Paragraph к коллекции документа Paragraphs.

Одним из наиболее важных объектов в Word является Range. A Диапазон представляет собой кусок документа. Код устанавливает текст нового абзаца в «Кривую хризантемы». Затем он устанавливает стиль объекта Range в «Заголовок 1.». Снова обратите внимание на нечетный способ, которым он должен поместить значение в переменную перед вызовом set_Style, чтобы он мог передавать имя стиля по ссылке.

Затем код вызывает метод Range объекта InsertParagraphAfter. Это добавляет метку абзаца после текущего текста объекта Range и обновляет Range, чтобы перейти к новому абзацу. Теперь Range готов добавить больше текста после первого абзаца.

Код снова устанавливает текст объекта Range для добавления нового текста и вызовов InsertParagraphAfter снова.

Далее код добавляет некоторый текст, отформатированный как код с шрифтом Courier New. Он сохраняет имя текущего шрифта и устанавливает шрифт объекта Range в Courier New. С этого момента новый текст будет иметь этот шрифт.

Код снова устанавливает текст объекта Range и добавляет новый знак абзаца. Затем он восстанавливает исходное имя шрифта, поэтому будущий текст будет в исходном шрифте.

Затем код вызывает метод SaveAs документа Word для сохранения нового документа. Это перезаписывает любой существующий файл с этим именем без предупреждения. Если вы хотите убедиться, что файл еще не существует, используйте File.Exists для проверки.

Наконец, код закрывает документ Word и приложение Word.

Источник: http://csharphelper.com/blog/2014/11/create-a-word-document-in-c/

I have a project where I would like to generate a report export in MS Word format. The report will include images/graphs, tables, and text. What is the best way to do this? Third party tools? What are your experiences?

Peter Mortensen's user avatar

asked Aug 13, 2008 at 22:07

Schmidty's user avatar

1

The answer is going to depend slightly upon if the application is running on a server or if it is running on the client machine. If you are running on a server then you are going to want to use one of the XML based office generation formats as there are know issues when using Office Automation on a server.

However, if you are working on the client machine then you have a choice of either using Office Automation or using the Office Open XML format (see links below), which is supported by Microsoft Office 2000 and up either natively or through service packs. One draw back to this though is that you might not be able to embed some kinds of graphs or images that you wish to show.

The best way to go about things will all depend sightly upon how much time you have to invest in development. If you go the route of Office Automation there are quite a few good tutorials out there that can be found via Google and is fairly simple to learn. However, the Open Office XML format is fairly new so you might find the learning curve to be a bit higher.

Office Open XML Iinformation

  • Office Open XML — http://en.wikipedia.org/wiki/Office_Open_XML
  • OpenXML Developer — http://openxmldeveloper.org/default.aspx
  • Introducing the Office (2007) Open XML File Formats — http://msdn.microsoft.com/en-us/library/aa338205.aspx

answered Aug 13, 2008 at 22:19

rjzii's user avatar

rjziirjzii

14.1k12 gold badges82 silver badges119 bronze badges

1

DocX free library for creating DocX documents, actively developed and very easy and intuitive to use. Since CodePlex is dying, project has moved to github.

answered Jul 22, 2010 at 15:07

MadBoy's user avatar

MadBoyMadBoy

10.8k23 gold badges95 silver badges155 bronze badges

I have spent the last week or so getting up to speed on Office Open XML. We have a database application that stores survey data that we want to report in Microsoft Word. You can actually create Word 2007 (docx) files from scratch in C#. The Open XML SDK version 2 includes a cool application called the Document Reflector that will actually provide the C# code to fully recreate a Word document. You can use parts or all of the code, and substitute the bits you want to change on the fly. The help file included with the SDK has some good code samples as well.

There is no need for the Office Interop or any other Office software on the server — the new formats are 100% XML.

Peter Mortensen's user avatar

answered May 20, 2009 at 13:40

Have you considered using .RTF as an alternative?

It supports embedding images and tables as well as text, opens by default using Microsoft Word and whilst it’s featureset is more limited (count out any advanced formatting) for something that looks and feels and opens like a Word document it’s not far off.

Your end users probably won’t notice.

answered Aug 14, 2008 at 14:43

DavidWhitney's user avatar

DavidWhitneyDavidWhitney

4,2704 gold badges23 silver badges30 bronze badges

1

I have found Aspose Words to be the best as not everybody can open Office Open XML/*.docx format files and the Word interop and Word automation can be buggy. Aspose Words supports most document file types from Word 97 upwards.

It is a pay-for component but has great support. The other alternative as already suggested is RTF.

Peter Mortensen's user avatar

answered Aug 14, 2008 at 14:57

John's user avatar

JohnJohn

29.4k18 gold badges92 silver badges128 bronze badges

1

To generate Word documents with Office Automation within .NET, specifically in C# or VB.NET:

  1. Add the Microsoft.Office.Interop.Word assembly reference to your project. The path is Visual Studio Tools for OfficePIAOffice11Microsoft.Office.Interop.Word.dll.

  2. Follow the Microsoft code example
    you can find here: http://support.microsoft.com/kb/316384/en-us.

Peter Mortensen's user avatar

answered Dec 1, 2009 at 22:50

Marcello Belguardi's user avatar

Schmidty, if you want to generate Word documents on a web server you will need a licence for each client (not just the web server). See this section in the first link Rob posted:

«Besides the technical problems, you must also consider licensing issues. Current licensing guidelines prevent Office applications from being used on a server to service client requests, unless those clients themselves have licensed copies of Office. Using server-side Automation to provide Office functionality to unlicensed workstations is not covered by the End User License Agreement (EULA).»

If you meet the licensing requirements, I think you will need to use COM Interop — to be specific, the Office XP Primary Interop Assemblies.

answered Aug 13, 2008 at 23:21

Luke Girvin's user avatar

Luke GirvinLuke Girvin

13.1k8 gold badges63 silver badges84 bronze badges

Check out VSTO (Visual Studio Tools for Office). It is fairly simple to create a Word template, inject an xml data island into it, then send it to the client. When the user opens the doc in Word, Word reads the xml and transforms it into WordML and renders it. You will want to look at the ServerDocument class of the VSTO library. No extra licensing is required from my experience.

answered Aug 14, 2008 at 15:03

DancesWithBamboo's user avatar

DancesWithBambooDancesWithBamboo

4,1651 gold badge18 silver badges20 bronze badges

I have had good success using the Syncfusion Backoffice DocIO which supports doc and docx formats.

In prior releases it did not support everything in word, but accoriding to your list we tested it with tables and text as a mail merge approach and it worked fine.

Not sure about the import of images though. On their blurb page http://www.syncfusion.com/products/DocIO/Backoffice/features/default.aspx it says

Blockquote
Essential DocIO has support for inserting both Scalar and Vector images into the document, in almost all formats. Bitmap, gif, png and tiff are some of the common image types supported.

So its worth considering.

As others have mentioned you can build up a RTF document, there are some good RTF libraries around for .net like http://www.codeproject.com/KB/string/nrtftree.aspx

answered Apr 9, 2009 at 4:07

Jafin's user avatar

JafinJafin

4,0231 gold badge40 silver badges51 bronze badges

I faced this problem and created a small library for this. It was used in several projects and then I decided to publish it. It is free and very very simple but I’m sure it will help with you with the task. Invoke the Office Open XML Library, http://invoke.co.nz/products/docx.aspx.

Peter Mortensen's user avatar

answered Dec 25, 2008 at 21:51

I’ve written a blog post series on Open XML WordprocessingML document generation. My approach is that you create a template document that contains content controls, and in each content control you write an XPath expression that defines how to retrieve the content from an XML document that contains the data that drives the document generation process. The code is free, and is licensed under the the Microsoft Reciprocal License (Ms-RL). In that same blog post series, I also explore an approach where you write C# code in content controls. The document generation process then processes the template document and generates a C# program that generates the desired documents. One advantage of this approach is that you can use any data source as the source of data for the document generation process. That code is also licenced under the Microsoft Reciprocal License.

answered May 12, 2011 at 3:50

Eric White's user avatar

Eric WhiteEric White

1,85111 silver badges14 bronze badges

I currently do this exact thing.

If the document isn’t very big, doesn’t contain images and such, then I store it as an RTF with #MergeFields# in it and simply replace them with content, sending the result down to the user as an RTF.

For larger documents, including images and dynamically inserted images, I save the initial Word document as a Single Webpage *.mht file containing the #MergeFields# again. I then do the same as above. Using this, I can easily render a DataTable with some basic Html table tags and replace one of the #MergeFields# with a whole table.

Images can be stored on your server and the url embedded into the document too.

Interestingly, the new Office 2007 file formats are actually zip files — if you rename the extension to .zip you can open them up and see their contents. This means you should be able to switch content such as images in and out using a simple C# zip library.

answered Sep 15, 2008 at 11:05

littlecharva's user avatar

littlecharvalittlecharva

4,2147 gold badges44 silver badges52 bronze badges

@Dale Ragan: That will work for the Office 2003 XML format, but that’s not portable (as, say, .doc or .docx files would be).

To read/write those, you’ll need to use the Word Object Library ActiveX control:

http://www.codeproject.com/KB/aspnet/wordapplication.aspx

answered Aug 13, 2008 at 22:21

TheSmurf's user avatar

TheSmurfTheSmurf

15.3k3 gold badges39 silver badges48 bronze badges

0

@Danny Smurf: Actually this article describes what will become the Office Open XML format which Rob answered with. I will pay more attention to the links I post for now on to make sure there not obsolete. I actually did a search on WordML, which is what it was called at the time.

I believe that the Office Open XML format is the best way to go.

answered Aug 13, 2008 at 22:34

Dale Ragan's user avatar

Dale RaganDale Ragan

18.2k3 gold badges53 silver badges70 bronze badges

LibreOffice also supports headless interaction via API. Unfortunately there’s currently not much information about this feature yet.. :(

answered Nov 14, 2011 at 9:56

plaes's user avatar

plaesplaes

31.5k10 gold badges88 silver badges89 bronze badges

You could also use Word document generator. It can be used for client-side or server-side deployment. From the project description:

WordDocumentGenerator is an utility to generate Word documents from
templates using Visual Studio 2010 and Open XML 2.0 SDK.
WordDocumentGenerator helps generate Word documents both
non-refresh-able as well as refresh-able based on predefined templates
using minimum code changes. Content controls are used as placeholders
for document generation. It supports Word 2007 and Word 2010.

Grab it: http://worddocgenerator.codeplex.com/

Download SDK: http://www.microsoft.com/en-us/download/details.aspx?id=5124

answered Dec 27, 2012 at 19:08

Ricardo's user avatar

RicardoRicardo

5454 silver badges9 bronze badges

Another alternative is Windward Docgen (disclaimer — I’m the founder). With Windward you design the template in Word, including images, tables, graphs, gauges, and anything else you want. You can set tags where data from an XML or SQL datasource is inserted (including functionality like forEach loops, import, etc). And then generate the report to DOCX, PDF, HTML, etc.

answered Jun 6, 2012 at 22:37

David Thielen's user avatar

David ThielenDavid Thielen

27.4k33 gold badges112 silver badges190 bronze badges

3

Typewriters640

In a recent post, I extolled the virtues of a wonderful OSS library I had found for working with Excel data programmatically, LinqToExcel. In that post, I also mentioned a fantastic library for working with Word docs as well, and promised to discuss it in my next post. This is that post.

The big pain point in working with MS Word documents programmatically is . . . the Office Interop. To get almost anything done with Word (including simply pulling the text out of the document, you pretty much need to use Interop, which also means you have to have Word installed on the local machine which is consuming your application. Additionally, my understanding is that there are issues with doing Word automation on the server side.

Image by Mohylek — Some Rights Reserved

Interop is essentially a giant wrapper around the ugliness that is COM, and the abstraction layer is thin indeed. If you need to automate MS Office applications, Interop (or going all the way down to the COM level) is pretty much the only way to do it, and obviously, you need to have Office installed on the client machine for it to work at all.

Often times though, we don’t so much need to automate the office application directly so much as get at the contents of Office file (such as Word or Excel files). Dealing with all that Interop nastiness makes this more painful than it needs to be.

Thankfully, the open source DocX by Cathal Coffey solves both problems nicely, and unlike Interop, presents an easy-to-use, highly discoverable API for performing myriad manipulations/extractions against the Word document format (the .docx format, introduced as of Word 2007). Best of all, DocX does not require that Word or any other Office dependencies be installed on the client machine! The full source is available from Coffey’s Codeplex repo, or you can add DocX to your project using Nuget.

10/2/2013 — NOTE: It has been noted by several commentors on Reddit and elsewhere that the MS official library OpenXml serves the same purpose as Docx, and after all, is the «official» library. I disagree — the OpenXml library «does more» but is inherently more complex to use. While it most certainly offers additional functionality not present in DocX, the DocX library creates a much simpler and more meaningful abstraction for what I find to be the most common use-cases working with Word documents programmatically. As always, the choice of libraries is a matter of preference, and to me, one of «Right tool for the job.»  

1/23/2014 — NOTE: I mentioned in the opening paragraph the OSS project LinqToExcel, which is a fantastic library. However, LinqToExcel takes a dependency on the Access Database Engine, which can create issues when (for example) deploying to a remote server or other environment where administrative privileges may be limited. I discovered another OSS library with no such dependencies. You can read about it at  Use Cross-Platform/OSS ExcelDataReader to Read Excel Files with No Dependencies on Office or ACE 

In this post, we will look at a few of the basics for using this exceptionally useful library. Know that under the covers and with a little thought, there is a lot of functionality here beyond what we will look at in this article.

  • Getting Started — Create a Word Document Using the DocX Library
  • Use DocX to Add Formatted Paragraphs
  • Find and Replace Text Using DocX -Merge Templating, Anyone?
  • DocX Exposes Many of the Most Useful Parts of the Word Object Model
  • C#: Query Excel and .CSV Files Using LinqToExcel 
  • Additional Resources/Items of Interest

Add DocX to your project using Nuget

NOTE: When adding Nuget packages to your project, consider keeping source control bloat down by using Nuget Package Restore so that packages are downloaded automatically on build rather than cluttering up your repo.  

As with LinqToExcel, you can add the DocX library to your Visual Studio solution using the Nuget Package Manager Console by doing:

Install DocX using the Nuget Package Manager Console:
PM> Install-Package DocX

Alternatively, you can use the Solution Explorer. Right-click on the Solution, select «Manager Nuget Packages for Solution,» and type «DocX in the search box (make sure you have selected «Online» in the left-hand menu). When you have located the DocX package, click Install:

Install DocX using the Nuget Package Manager GUI in VS Solution Explorer:

get-docx-from-nuget

Getting Started – Create a Word Document Using the DocX Library

Wanna Quickly create a Word-compatible, .docx format document on the fly from your code? Do this (I am assuming you have Word installed on your local machine):

(Note – change the file path to reflect your own machine)

A Really Simple Example:
using Novacode;
using System;
using System.Diagnostics;
 
namespace BlogSandbox
{
    public class DocX_Examples
    {      
        public void CreateSampleDocument()
        {
            
            string fileName = @"D:UsersJohnDocumentsDocXExample.docx";
  
            
            var doc = DocX.Create(fileName);
  
            
            doc.InsertParagraph("This is my first paragraph");
  
            
            doc.Save();
  
            
            Process.Start("WINWORD.EXE", fileName);
        }
    }
}

Note in the above we need to add using Novacode; to our namespace imports at the top of the file. The DocX library is contained within this namespace. If you run the code above, a word document should open like this:

Output of Really Simple Example Code:

docx-simple-code-sample-1

What we did in the above example was:

  • Create an in-memory instance of a DocX object with a file name passed in as part of the constructor.
  • Insert a DocX.Paragraph object containing some text.
  • Save the result to disc as a properly formatted .docx file.

Until we execute the Save() method, we are working with the XML representation of our new document in memory. Once we save the file to disc, we find a standard Word-compatible file in our Documents/ directory.

Use DocX to Add Formatted Paragraphs – A More Useful Example

A slightly more useful example might be to create a document with some more complex formatted text:

Create Multiple Paragraphs with Basic Formatting:
public void CreateSampleDocument()
{
    string fileName = @"D:UsersJohnDocumentsDocXExample.docx";
    string headlineText = "Constitution of the United States";
    string paraOne = ""
        + "We the People of the United States, in Order to form a more perfect Union, "
        + "establish Justice, insure domestic Tranquility, provide for the common defence, "
        + "promote the general Welfare, and secure the Blessings of Liberty to ourselves "
        + "and our Posterity, do ordain and establish this Constitution for the United "
        + "States of America.";
  
    
    var headLineFormat = new Formatting();
    headLineFormat.FontFamily = new System.Drawing.FontFamily("Arial Black");
    headLineFormat.Size = 18D;
    headLineFormat.Position = 12;
  
    
    var paraFormat = new Formatting();
    paraFormat.FontFamily = new System.Drawing.FontFamily("Calibri");
    paraFormat.Size = 10D;
  
    
    var doc = DocX.Create(fileName);
  
    
    doc.InsertParagraph(headlineText, false, headLineFormat);
    doc.InsertParagraph(paraOne, false, paraFormat);
  
    
    doc.Save();
  
    
    Process.Start("WINWORD.EXE", fileName);
}

Here, we have created some Formatting objects in advance, and then passed them as parameters to the InsertParagraph method for each of the two paragraphs we create in our code. When the code executes, Word opens and we see this:

Output from Creating Multiple Formatted Paragraphs

docx-simple-code-sample-2

In the above, the FontFamily and Size properties of the Formatting object are self-evident. The Position property determines the spacing between the current paragraph and the next.

We can also grab a reference to a paragraph object itself and adjust various properties. Instead of creating a Formatting object for our headline like we did in the previous example, we could grab a reference as the return from the InsertParagraph method and muck about:

Applying Formatting to a Paragraph Using the Property Accessors:
Paragraph headline = doc.InsertParagraph(headlineText);
headline.Color(System.Drawing.Color.Blue);
headline.Font(new System.Drawing.FontFamily("Comic Sans MS"));
headline.Bold();
headline.Position(12D);
headline.FontSize(18D);

This time, when the program executes, we see THIS:

docx-simple-code-sample-3-comic-sans

OH NO YOU DID NOT!

Yes, yes I DID print that headline in Comic Sans. Just, you know, so you could see the difference in formatting.

There is a lot that can be done with text formatting in a DocX document. Headers/Footers, paragraphs, and individual words and characters. Importantly, most of the things you might go looking for are easily discoverable – in other words, the author has done a great job building out his API.

Find and Replace Text Using DocX — Merge Templating, Anyone?

Of course, one of the most common things we might want to do is scan a pre-existing document, and replace certain text. Think templating here. For example, performing a standard Word Merge is not very doable on your web server, but using DocX, we can accomplish the same thing. The following example is simple due to space constraints, but you can see the possibilities:

First, just for kicks, we will create an initial document programmatically in one method, then write another method to find and replace certain text in the document:

Create a Sample Document:
private DocX GetRejectionLetterTemplate()
{
    
    string fileName = @"D:UsersJohnDocumentsDocXExample.docx";
  
    
    string headerText = "Rejection Letter";
    string letterBodyText = DateTime.Now.ToShortDateString();
    string paraTwo = ""
        + "Dear %APPLICANT%" + Environment.NewLine + Environment.NewLine
        + "I am writing to thank you for your resume. Unfortunately, your skills and "
        + "experience do not match our needs at the present time. We will keep your "
        + "resume in our circular file for future reference. Don't call us, " 
        + "we'll call you. "
  
        + Environment.NewLine + Environment.NewLine
        + "Sincerely, "
        + Environment.NewLine + Environment.NewLine
        + "Jim Smith, Corporate Hiring Manager";
  
    
    var titleFormat = new Formatting();
    titleFormat.FontFamily = new System.Drawing.FontFamily("Arial Black");
    titleFormat.Size = 18D;
    titleFormat.Position = 12;
  
    
    var paraFormat = new Formatting();
    paraFormat.FontFamily = new System.Drawing.FontFamily("Calibri");
    paraFormat.Size = 10D;
    titleFormat.Position = 12;
  
    
    var doc = DocX.Create(fileName);
  
    
    Paragraph title = doc.InsertParagraph(headerText, false, titleFormat);
    title.Alignment = Alignment.center;
  
    doc.InsertParagraph(Environment.NewLine);
    Paragraph letterBody = doc.InsertParagraph(letterBodyText, false, paraFormat);
    letterBody.Alignment = Alignment.both;
  
    doc.InsertParagraph(Environment.NewLine);
    doc.InsertParagraph(paraTwo, false, paraFormat);
  
    return doc;
}

See the %APPLICANT% placeholder? That is my replacement target (a poor-man’s merge field, if you will). Now that we have a private method to generate a document template of sorts, let’s add a public method to perform a replacement action:

Find and Replace Text in a Word Document Using DocX:
public void CreateRejectionLetter(string applicantField, string applicantName)
{
    
    string fileNameTemplate = @"D:UsersJohnDocumentsRejection-Letter-{0}-{1}.docx";
  
    
    
    string outputFileName = 
    string.Format(fileNameTemplate, applicantName, DateTime.Now.ToString("MM-dd-yy"));
  
    
    DocX letter = this.GetRejectionLetterTemplate();
  
    
    letter.ReplaceText(applicantField, applicantName);
  
    
    letter.SaveAs(outputFileName);
  
    
    Process.Start("WINWORD.EXE", """ + outputFileName + """);
}

Now, when we run the code above, our output is thus:

docx-rejection-letter-sample

Obviously, the preceding example was a little contrived and overly simple. But you can see the potential . . . If our letter contained additional «merge fields, we could just as easily pass in a Dictionary<string, string>, where the Dictionary contains one or more Key Value Pairs containing a replacement target and a replacement value. Then we could iterate,  using the Dictionary Keys as the search string, and replace with the Dictionary values.

DocX Exposes Many of the Most Useful Parts of the Word Object Model

In this quick article, we have only scratched the surface. DocX exposes most of the stuff we commonly wish we could get to within a Word document (Tables, Pictures, Headers, Footers, Shapes, etc.) without forcing us to navigate the crusty Interop model. This also saves us from some of the COM de-referencing issues which often arise when automating Word within an application. Ever had a bunch of «orphaned» instances of Word (or Excel, etc.) running in the background, visible only in the Windows Task Manager? Yeah, I thought so . . .

If you need to generate or work with Word documents on a server, this is a great tool as well. No dependencies on MS Office, no need to have Word running. You can generate Word documents on the fly, and/or from templates, ready to be downloaded.

I strongly recommend you check out the project on Codeplex. Also, the project author, Cathal Coffey, discusses much of the DocX functionality on his own blog. If you dig DocX, drop by and let him know. He’s really done a fantastic job.

Additional Resources/Items of Interest

  • Extending Identity Accounts and Implementing Role-Based Authentication in ASP.NET MVC 5
  • C#: Query Excel and .CSV Files Using LinqToExcel
  • Splitting and Merging Pdf Files in C# Using iTextSharp
  • Working with PDF Files in C# Using PdfBox and IKVM
  • Customizing Routes in ASP.NET MVC
  • Routing Basics in ASP.NET MVC
  • Building Out a Clean, REST-ful Web Api Service with a Minimal Web Api Project
  • Creating a Clean, Minimal-Footprint ASP.NET WebAPI Project with VS 2012 and ASP.NET MVC 4

My name is John Atten, and my username on many of my online accounts is xivSolutions. I am Fascinated by all things technology and software development. I work mostly with C#, Javascript/Node.js, Various flavors of databases, and anything else I find interesting. I am always looking for new information, and value your feedback (especially where I got something wrong!)

In previous article, I have mentioned to convert HTML to word document using javascript, now in this article, I have provided working example to create word document or you can say generate word document using DocX library in C#, step by step.

Step 1: We will create a new console application using which we will generate our word document, so Open your Visual Studio and create a new console application by navigating to File-> New -> Project -> Select «Windows desktop» from left pane and Select «Console Application» from right-pane, then name it and Click «Ok».

create-word-document-csharp-min.png

Step 2: Install DocX library in your console application, using NuGet, navigate to «Tools» -> «NuGet Package Manager console» -> «Manage Nuget Packages for solution «-> Select «Browse» tab and search «DocX», select it and Install it in your project.

install-docx-package-min.png

Note: DocX is free to use, .NET library that allows developers to manipulate Microsoft Word files, in an easy and intuitive manner. DocX is fast, lightweight and best of all it does not require Microsoft Word or Office to be installed.

Step 3: Navigate to «Program.cs» to use below code


using Xceed.Document.NET;
using Xceed.Words.NET;

namespace CreateWordDocument
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = @"E:DocxExamplesampleWordFile.docx";

            var doc = DocX.Create(fileName); //create docx word document

            doc.AddHeaders(); //add header (optional)
            doc.AddFooters(); //add footer in this document (optional code)

            // Force the first page to have a different Header and Footer.
            doc.DifferentFirstPage = true;

            doc.Headers.First.InsertParagraph("This is the ").Append("first").Bold().Append(" page header");// Insert a Paragraph into the first Header.
            doc.Footers.First.InsertParagraph("Page ").AppendPageNumber(PageNumberFormat.normal).Append(" of ").AppendPageCount(PageNumberFormat.normal); // add footer with page number

            doc.InsertParagraph("Hello Word"); // inserts a new paragraph with text

            doc.Save(); // save changes to file
        }
    }
}

In the above code, we are first creating a fileName and then creating .docx word document using DocX NuGet Package.

We are also adding header and footer in the document, this is optional code and we can skip it, but for example purpose I have added the code.

And we are simply adding a paragraph here, then saving the document using «doc.Save()».

Once you will build and run the above code, you can see a new word document is created and can be viewed in your file location ‘E:DocxExamplesampleWordFile.docx’

Here is the document created using above code

word-document-generate-csharp-min.png

Adding Images in Word Document using DocX in C#

In the above code, we are just adding header/footer and a simple paragraph, if you want you can also add a image file into word document using DocX, here is the sample code for it.


using System.IO;
using Xceed.Document.NET;
using Xceed.Words.NET;

namespace CreateWordDocument
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = @"E:DocxExamplesampleWordFile.docx";

            var doc = DocX.Create(fileName); //create docx word document

            var url = System.AppContext.BaseDirectory; //return /bin/debug location

            // Add a simple image from disk.
            var image = doc.AddImage(new FileStream(url + "/sample-image.jpg", FileMode.Open, FileAccess.Read) );
            var picture = image.CreatePicture(200f,200f);
            var p = doc.InsertParagraph("Here is a simple picture added from disk");
            p.AppendPicture(picture);



            doc.Save(); // save changes to file
        }
    }
}

once, you will build and run above code in your console application, you will see word document as below

word-document-generate-csharp-with-image-min.png

Add table content to Word document using DocX in C#

If you want you can also create table inside word document using DocX, so here is the sample code for it in C#

using System.IO;
using System.Linq;
using Xceed.Document.NET;
using Xceed.Words.NET;

namespace CreateWordDocument
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = @"E:DocxExamplesampleWordFile.docx";

            var doc = DocX.Create(fileName);

            //Create Table with 2 rows and 4 columns.  
            Table t = doc.AddTable(2, 4);
            t.Alignment = Alignment.center; //align center

            //Fill first row adding text in four column
            t.Rows[0].Cells[0].Paragraphs.First().Append("AA");
            t.Rows[0].Cells[1].Paragraphs.First().Append("BB");
            t.Rows[0].Cells[2].Paragraphs.First().Append("CC");
            t.Rows[0].Cells[3].Paragraphs.First().Append("DD");

            //second row by adding text in four column
            t.Rows[1].Cells[0].Paragraphs.First().Append("EE");
            t.Rows[1].Cells[1].Paragraphs.First().Append("FF");
            t.Rows[1].Cells[2].Paragraphs.First().Append("GG");
            t.Rows[1].Cells[3].Paragraphs.First().Append("HH");
            //insert table in doc
            doc.InsertTable(t);

            doc.Save(); // save changes to file
        }
    }
}

In the above code, we are first creating table of 2 Rows and 4 Columns, then filling columns row by row using C#.

You may also like to read:

Read Excel using C#

Read PDF using C#

Read text file using C#

Create excel in C# without using interop

Понравилась статья? Поделить с друзьями:
  • Как создавать word xml файлы
  • Как соединить функции если в excel
  • Как соединить фамилию с инициалами в excel
  • Как соединить фамилию имя отчество в excel
  • Как соединить файлы excel в один файл