Home > Computers and Internet > How to create Word Document programatically using c#

How to create Word Document programatically using c#

private void SaveDocument()

    {
        object missing = System.Reflection.Missing.Value;
        dtSections = UpdateRows();
        try
        {
            ViewState["SectionName"] = string.Empty;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                #region Creating Word Document with Proposal Name
                object oTemplate = ConfigurationManager.AppSettings["DocumentTemplatePath"].ToString();
                oWordApp = (Microsoft.Office.Interop.Word.Application)Activator.CreateInstance(Type.GetTypeFromProgID("Word.Application"));
                oWordDoc = oWordApp.Documents.Add(ref oTemplate, ref missing, ref missing, ref missing);
                object wordcount = oWordDoc.Content.End – 1;
                //string aa = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
                object fileFormat = (object)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;

                oWordDoc.ShowSpellingErrors = false;//Forcefully hide the Spelling Errors
                oWordDoc.ActiveWindow.ActivePane.View.Zoom.Percentage = 100;// Forcefully set the Zoom percentage to 100% when opening the document

                Microsoft.Office.Interop.Word.Range rng = oWordDoc.Range(ref wordcount, ref missing);
                object styleHeading1 = "Proposal Sections";
                rng.InsertAfter(styleHeading1.ToString() + "\n ");
                object range1 = rng;
                Microsoft.Office.Interop.Word.Range rng2;
                object range2 = missing;
                string sectionName = string.Empty;
                Microsoft.Office.Interop.Word.Paragraph para2 = null;
                bool temp = false;
                for (int rowindex = 0; rowindex < gvGuidedSearch.Rows.Count; rowindex++)

                {
                    if (((CheckBox)gvGuidedSearch.Rows[rowindex].FindControl("chkSelectSection")).Checked)

                    {
                        sectionName = ((Literal)gvGuidedSearch.Rows[rowindex].FindControl("ltSectionName")).Text;

                        if (ViewState["SectionName"] != null)
                        {
                            if (sectionName == ViewState["SectionName"].ToString())
                            {
                                para2 = oWordDoc.Content.Paragraphs.Add(ref missing);
                                para2.Range.Font.Size = 10;
                                para2.Range.Text = ((Literal)gvGuidedSearch.Rows[rowindex].FindControl("ltSectionDetail")).Text;
                                para2.Range.Paragraphs.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;
                                para2.Range.InsertParagraphAfter();
                                temp = true;
                            }
                            else
                            {
                                if (temp)
                                {
                                    rng2 = oWordDoc.Range(ref wordcount, ref missing);
                                    range2 = rng2;
                                    string replaceChar = ViewState["SectionName"].ToString();
                                    replaceChar = replaceChar.Replace(" ", "_");
                                    replaceChar = replaceChar.Replace(":", "11");
                                    replaceChar = replaceChar.Replace("&", "33");

                                    para2.Range.Bookmarks.Add(replaceChar, ref range2);
                                    temp = false;
                                    //ViewState["SectionName"] = sectionName;
                                }

                                ViewState["SectionName"] = sectionName;
                                rng.InsertAfter(sectionName + "\n");
                                wordcount = oWordDoc.Content.End – 1;
                                rng2 = oWordDoc.Range(ref wordcount, ref missing);
                                range2 = rng2;
                                para2 = oWordDoc.Content.Paragraphs.Add(ref missing);
                                para2.Range.Font.Size = 10;
                                para2.Range.Text = ((Literal)gvGuidedSearch.Rows[rowindex].FindControl("ltSectionDetail")).Text;

                                para2.Range.Paragraphs.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;
                                para2.Range.InsertParagraphAfter();
                                temp = true;

                            }
                        }
                    }
                }
                if (temp)
                {
                    rng2 = oWordDoc.Range(ref wordcount, ref missing);
                    range2 = rng2;
                    string replaceChar = ViewState["SectionName"].ToString();
                    replaceChar = replaceChar.Replace(" ", "_");
                    replaceChar = replaceChar.Replace(":", "11");
                    replaceChar = replaceChar.Replace("&", "33");
                    para2.Range.Bookmarks.Add(replaceChar, ref range2);

                }
                object filename = ConfigurationManager.AppSettings["ProposalFolderPath"].ToString() + txtProposalName.Text.Trim();
                oWordDoc.SaveAs(ref filename, ref fileFormat, 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);

                oWordApp.Quit(ref missing, ref missing, ref missing);

                System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordApp);

                System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordDoc);

                #endregion

                #region Getting users Data like ID,Login Name

                Hashtable htSeesionData = (Hashtable)Session["sessionHtUser"];
                SPFieldUserValueCollection values = new SPFieldUserValueCollection();
                using (currentSite = new SPSite(ConfigurationManager.AppSettings["SiteURL"].ToString()))
                {
                    currentWeb = currentSite.OpenWeb();

                    for (int rowIndex = 0; rowIndex < dtSections.Rows.Count; rowIndex++)

                    {
                        SPUser sectionUser = currentWeb.SiteUsers.GetByEmail(dtSections.Rows[rowIndex][SECTIONOWNERIDCOLUMN].ToString());

                        SPFieldUserValue fuv = new SPFieldUserValue(currentWeb, sectionUser.ID, sectionUser.LoginName);

                        values.Add(fuv);
                    }
                }
                #endregion
            });
        }

        catch (Exception ex)
        {

 

            EventLog.WriteEntry("ProposeBuilder", ex.Message, EventLogEntryType.Error);
        }

        finally
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordApp);

            System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordDoc);

            //oWordApp.Application.Quit(ref missing, ref missing, ref missing);
        }
    }

Advertisements
  1. 15/06/2014 at 2:03 pm

    I visited many web pages but the audio feature for
    audio songs existing at this web page is actually wonderful.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: