Article
    C#
    ADO.Net
    .NET
    ASP.Net & Web Forms
    Custom Controls
    Web Development
    Exception Handling
    XML
    Database
    Security in .Net
    Testing
    Web Services
    Windows Services
    Windows Controls
    WCF
    AJAX
    WPF
    XAML
    Reporting
    Setup
    VB.Net
    LINQ
    JQuery
    SilverLight
    JavaScript
    HTML5
    Crystal Report
    Cloud Computing
    Share Point
    Visual C++
    MVC
    Android
    PHP
    Java
    HTML
    WordPress
    Joomla
    Products
    Drupal
    Windows Phone
    JSON
    LightSwitch
    iPhone/iPad
    Ruby on Rails
    IIS 7
    Windows 8
    CSS/CSS3
    Excel
    MS Access
    Shortcut Keys
    Visual SourceSafe
    Team Foundation Server
    API(s)
    Sencha-Touch
    Single Page App
    Bootstrap
Follow Us
Follow _MindStick_ on Twitter View MindStick Software's LinkedIn profile View MindStick Software's Facebook profile
Top Contributor
Advertisement
Advertise with Us
Mindstick
Article Article  Forum Forum  Blog Blog  Quiz Quiz  Beginner Beginner  Careers Careers  Contact Contact  Login Login  
Home | Product | Services | About Us | Interview | DeveloperSection | Submit an Article | Submit Blog

Home >> C# >> Editing MS Word document in CSharp .NET
Editing MS Word document in CSharp .NET
Editing MS Word document in CSharp .NET


by Uttam Misra on 7/12/2010 8:10:38 PM

Views: 17704       Comments: 2

Editing MS Word document through C#.Net

Here I am going to demonstrate how to create and edit MS Word file through C#.Net

Example

To create or edit MS Word document, first of all we need to add two references to our project.

Coding

Creating document

private void btnCreate_Click(object sender, EventArgs e)

        {

            try

            {

//creating object for missing value

                object missing = System.Reflection.Missing.Value;

//object for end of file

                object endofdoc = "\\endofdoc";

 

//creating instance of word application

Microsoft.Office.Interop.Word._Application w = new Microsoft.Office.Interop.Word.Application();

//creating instance of word document

                Microsoft.Office.Interop.Word._Document doc;

//setting status of application to visible

                w.Visible = true;

//creating new document

    doc = w.Documents.Add(ref missing, ref missing, ref missing,     ref missing);

//adding paragraph to document

                Microsoft.Office.Interop.Word.Paragraph para1;

                para1 = doc.Content.Paragraphs.Add(ref missing);

                object styleHeading1 = "Heading 1";

                para1.Range.set_Style(ref styleHeading1);

                para1.Range.Text = "Heading One";

                para1.Range.Font.Bold = 1;

                para1.Format.SpaceAfter = 24;

                para1.Range.InsertParagraphAfter();

//creating second paragraph

                Microsoft.Office.Interop.Word.Paragraph para2;

                para2 = doc.Content.Paragraphs.Add(ref missing);               

    para2.Range.Text = "Heading OneHeading OneHeading OneHeading OneHeading OneHeading OneHeading"+ '\n'+"OneHeading OneHeading OneHeading OneHeading OneHeading OneHeading One";

                para2.Range.Font.Bold = 1;

                para2.Format.SpaceAfter = 24;

                para2.Range.InsertParagraphAfter();

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

 

Editing document

        private void btnEdit_Click(object sender, EventArgs e)

        {

//creating instance of word application

    Microsoft.Office.Interop.Word._Application w = new Microsoft.Office.Interop.Word.Application();               

                object path = @"C:\table.doc";

                object read = "ReadWrite";

                object readOnly = false;

                object o = System.Reflection.Missing.Value;

//opening document

    Microsoft.Office.Interop.Word._Document oDoc = w.Documents.Open(ref path, ref o, ref readOnly, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);

 

                try

                {              

//loop for each paragraph in document

foreach (Microsoft.Office.Interop.Word.Paragraph p in oDoc.Paragraphs)

                {

                    Microsoft.Office.Interop.Word.Range rng = p.Range;

  Microsoft.Office.Interop.Word.Style styl = rng.get_Style() as Microsoft.Office.Interop.Word.Style;                   

//checking if document containg table

if ((bool)rng.get_Information (Microsoft.Office.Interop.Word.WdInformation.wdWithInTable)

                    == true)

                    {

//loop for each cell in table

   foreach (Microsoft.Office.Interop.Word.Cell c in rng.Cells)

                        {

                            if (rng.Cells.Count > 0)

                            {

            //checking for desired field in table

                                if (c.Range.Text.ToString().Contains("ID"))

                  //editing values in tables.

                                    c.Next.Range.Text = "1";

                                if (c.Range.Text.ToString().Contains("Name"))

                                    c.Next.Range.Text = "Haider";

  if (c.Range.Text.ToString().Contains("Address"))

                                    c.Next.Range.Text = "Allahabad";                    

                            }

                        }

//saving document

                        oDoc.Save();

                    }                  

                }

//closing document

                oDoc.Close(ref o,ref o,ref o);

            }

            catch (Exception ex)

            {

                oDoc.Close(ref o, ref o, ref o);

                MessageBox.Show(ex.Message);

            }

           

        }

Screen shot

Before editing

After editing

Report Abuse Form
Reason:    
 


Another way to create and edit Word files in C#
by James Howard 2/15/2012 8:28:10 AM
Hi,

you can also very easily C# create Word and edit Word files with this .NET Word component.

Here is a sample code that shows how to create and C# edit Word file like the one in the article:

// Create new empty document.
var document = new DocumentModel();

// Add a table to the document.
document.Sections.Add(
    new Section(document,
        new Table(document,
            new TableRow(document,
                new TableCell(document, new Paragraph(document, "ID")),
                new TableCell(document)),
            new TableRow(document,
                new TableCell(document, new Paragraph(document, "Name")),
                new TableCell(document)),
            new TableRow(document,
                new TableCell(document, new Paragraph(document, "Address")),
                new TableCell(document)))));

// Save the document to a file.
document.Save("Document.docx", SaveOptions.DocxDefault);

// Load a document from the file.
document = DocumentModel.Load("Document.docx", LoadOptions.DocxDefault);

// Retrieve a table from the document.
var table = document.Sections[0].Blocks.Cast<Table>(0);

// Edit the table second column - insert data.
table.Rows[0].Cells[1].Blocks.Cast<Paragraph>(0).Inlines.Add(new Run(document, "1"));
table.Rows[1].Cells[1].Blocks.Cast<Paragraph>(0).Inlines.Add(new Run(document, "Haider"));
table.Rows[2].Cells[1].Blocks.Cast<Paragraph>(0).Inlines.Add(new Run(document, "Allahabad"));

// Save the document to a file.
document.Save("Document.docx", SaveOptions.DocxDefault);
Report Abuse

This comment control
by thomas hanrahan 7/14/2012 1:29:20 PM
I've been searching everywhere for a control to add to my win form that is identical to this commenting control that has all the editing controls, how did you create it???  any help would be hugely appreciated
Report Abuse
Title :
Comment :
Text ColorBackground Color
BoldItalicUnderline
LeftCenterRightJustify
Ordered ListBulleted List
IndentOutdent
Horizontal Rule
SubscriptSuperscript
HyperlinkImage
Design ModeDesign
View HtmlHtml
     
 
Latest Article by Uttam MisraRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Latest BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Top Viewed ArticlesRSS Feed
    
    
    
    
    
    
    
    
    
    
Top Viewed BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
Latest Interview QuestionsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Total Online Users: 5195
Advertisement
MindStick Cleaner
Advertise with Us
  
Copyright © 2009 - 2014MindStick. All Rights Reserved.