Getting a textbox value from a word document using ASP.NET? - c#

I have a very basic web application written in ASP.NET(C#) and a basic Microsoft Word (2007) document that contains a text box and a dropdown list.
In my web application code behind file I would like to call the textbox control and a dropdown control by name and extract the values from them.
Any documentation that I have found online simply reads or writes a word document but I can't seem to find anything on accessing controls and extracting the values from them.
Any help would be greatly appreciated
Thank You
This is the only code that I have at the minute that does anything with the word document. It finds the word doc and opens it:
//File path of the word document that contains the required values
string filePath = #"C:\Users\murphycm\Desktop\PlacesFile.docm";
object fileToOpen = (object)filePath;
//CREATING OBJECTS OF WORD AND DOCUMENT
Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document oWordDoc = new Microsoft.Office.Interop.Word.Document();
oWordDoc = oWord.Documents.Open(ref fileToOpen);

Unless you are going to install Microsoft Office on your server, I would recommend using the Open XML SDK 2.5 from Microsoft. With the SDK you can manipulate Microsoft Office documents for Office 2007 and higher:
http://www.microsoft.com/en-us/download/details.aspx?id=30425
Here's some code for getting text from a TextBox using both the OpenXML and Office Interop methods:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Word = Microsoft.Office.Interop.Word;
namespace OpenXMLSDKTest
{
class Program
{
static void Main(string[] args)
{
// Open XML Method
object fileName = #"OpenXmlTest.docx";
using (WordprocessingDocument myDocument = WordprocessingDocument.Open(fileName.ToString(), true))
{
var textbox = myDocument.MainDocumentPart.Document.Descendants<TextBoxContent>().First();
Console.WriteLine(textbox.InnerText);
}
// Office Interop Method
object missing = System.Reflection.Missing.Value;
object readOnly = false;
object isVisible = true;
Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
wordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);
object firstShape = 1;
string textFrameText = wordApp.ActiveDocument.Shapes.get_Item(ref firstShape).TextFrame.TextRange.Text;
wordApp.Quit(ref missing, ref missing, ref missing);
Console.WriteLine(textFrameText);
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}

public List<string> GetTagsFromNewTemplate(string filePath)
{
var tags = new HashSet<string>();
using (WordprocessingDocument myDocument = WordprocessingDocument.Open(filePath, false))
{
var textbox = myDocument.MainDocumentPart.Document.Descendants<DocumentFormat.OpenXml.Wordprocessing.Tag>().Select(x => x.Val);
textbox.ForEach(x => tags.Add(x));
}
return tags.Distinct().ToList();
}

Related

How to compare image (Shape) present in each page of word document through Microsoft.Interop.Word using C#.Net?

I am using following code to replace image (Shape in Microsoft.Interop.Office.Word) of the word document with new image but what the requirement from client is that I need to check the 1st Image of the 1st page of the word document and then compare this image with image of the rest of the document and if match it get replaced with new image else not so need help on how can we compare two shapes(Images)
public void ReplaceWordImage(string FilePath)
{
Word.Document d = new Word.Document();
Word.Application WordApp;
WordApp = new Microsoft.Office.Interop.Word.Application();
bool headerImage = false;
try
{
object missing = System.Reflection.Missing.Value;
object yes = true;
object no = false;
object filename = #"D:/ImageToReplace/5.docx";
d = WordApp.Documents.Open(ref filename, ref missing, ref no, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref yes, ref missing, ref missing, ref missing, ref missing);
List<Word.ShapeRange> ranges = new List<Microsoft.Office.Interop.Word.ShapeRange>();
List<Word.ShapeRange> headerRanges = new List<Microsoft.Office.Interop.Word.ShapeRange>();
foreach (Word.Shape shape in d.Shapes)
{
if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoPicture)
{
shape.Delete();
foreach (Word.Range r in ranges)
`enter code here` {
r.InlineShapes.AddPicture(#"D:\Untitled.jpg", ref missing, ref missing);
break;
}
}
The Word object model doesn't provide anything to compare two images. The best what you could do is to save both on the disk and then try comparing the bytes representation of both. However, there is a better way to get the job done. The answer is the Open XML SDK which allows getting the bytes representation of images on the fly without saving them to a disk before. The Open XML SDK contains a class WordprocessingDocument that can manipulate a memory stream containing a WordDocument content. And MemoryStream can be converted using ToArray() to a byte[]. See Convert Word of interop object to byte [] without saving physically for more information.

How to access the menu bar in word programatically using c#

We have created a VSTO ribbon and installed under my machine. Whenever I open a word document I can see my ribbon available in the menu bar. Now I have created a console application and open the existing document but I am unable to access the VSTO menu item dynamically. Can anyone help me how to approach to access the menu items dynamically in c#
I have created a console application and opening the existing document using word interop but I am unable to find the menu lists. I have tried in VSTO but none of those worked out
Now I would like to access the VM form designer dynamically and click on the save button using c#:
I have this code:
Application wordApp = new Application
{
Visible = false
};
DirectoryInfo directoryInfo = new DirectoryInfo("D:\\WordPlugin\\AutomationApp\\AutomationApp\\Content\\Templates");
string tempFile = "D:\\WordPlugin\\AutomationApp\\AutomationApp\\Content\\Templates";
FileInfo[] fileInfo = directoryInfo.GetFiles();
object missing = Missing.Value;
object readOnly = false;
object isVisible = false;
foreach (FileInfo info in fileInfo)
{
object filename = info.FullName;
Document doc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);
doc.Activate();
//if (!info.Name.Contains(".docx"))
string newFileName = string.Format("{0}\\{1}", tempFile, info.Name.Replace(".doc", ".docx"));
doc.SaveAs2(newFileName, WdSaveFormat.wdFormatXMLDocument,
CompatibilityMode: WdCompatibilityMode.wdWord2013);
var documentAddIn = doc.Application.ActiveDocument;
}
I am hoping to find out how I can access the menu bar items - Home, Insert, Design and my VSTO menu item.

Word Document SaveAs2 in Format wdFormatDocument97

I'm using Microsoft Interop Word version 15.0.0.0 in order to create a new Word document, insert some text into it, and save it.
When I'm saving it using the following command:
document.SaveAs2(wordFilePath);
the document is saved in format DOCX.
But when I'm saving it using the following command:
document.SaveAs2(wordFilePath, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument97);
the document is seemingly saved as Word-97 DOC (Windows explorer display it with Word-97 DOC icon and type), but it is really internally saved as DOCX (I can see this in two ways: it has the same size of the corresponding DOCX, and when I open it with Word-2016 and select SaveAs, the default save format is DOCX!).
How can I save a document in real document-97 format?
Here's the function used to create a new Word document, whose type depends on the extension (DOC vs. DOCX) of given file path:
public static void TextToMsWordDocument(string body, string wordFilePath)
{
Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();
winword.Visible = false;
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
if (body != null)
{
document.Content.SetRange(0, 0);
document.Content.Text = (body + System.Environment.NewLine);
}
if (System.IO.Path.GetExtension(wordFilePath).ToLower() == "doc")
document.SaveAs2(wordFilePath, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument97);
else // Assuming a "docx" extension:
document.SaveAs2(wordFilePath);
document.Close(ref missing, ref missing, ref missing);
document = null;
winword.Quit(ref missing, ref missing, ref missing);
winword = null;
}
And here's the code used to call this function:
TextToMsWordDocument("abcdefghijklmnopqrstuvwxyz", "text.doc");
TextToMsWordDocument("abcdefghijklmnopqrstuvwxyz", "text.docx");
It's been a rather stupid error...compare ‘ == ".doc" ’ instead of ‘ == "doc"...
I didn't notice it due to the fact that when SaveAs2 received a file path with extension ".doc" and no WdSaveFormat, it - strangely enough- created a Word document file that had the problem I explained here...

Insert a whole file into MS word document programatically using C# (not content of file)

this is my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
object missing = System.Reflection.Missing.Value;
object fileName = #"C:\b.docx";
Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
Document adoc = WordApp.Documents.Open(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);
Range rngPic = adoc.Tables[1].Cell(1, 2).Range;
rngPic.InsertFile(#"C:\a.docx", ref missing, ref missing, ref missing, ref missing);
WordApp.Visible = true;
}
}
}
what my expectation is b.docx should contain the file a.docx rather the content of a.docx was added to the b.docx.
In clear to say i need to insert a.docx into b.docx using c# programmatically as we do insert object in word.
i need to add the whole file into the word document. not content of the file help me!!!
correction , suggestions, new codes are most welcomed.
please help me.

programmatically insert mail mergefield into hyperlink in a word document

I'm trying to figure out how to programmatically insert mail mergefield into hyperlink in a word document.
In ms word application this is easily accomplished with the following code when in code-view(ALT+F9):
{HYPERLINK "http://example.com?id={MERGEFILED ID}"}
I consulted stackoverflow and google but came up empty-handed.
How could I accomplish something like above snippet via C# word interoperability library?
Right now this is what I have:
using mso = Microsoft.Office.Interop.Word;
public class Test
{
public void GenerateDynamicHyperlinkWithMergeField()
{
mso.Application app = new mso.Application();
object missing = System.Reflection.Missing.Value;
mso.Document doc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing);
mso.Range range = app.Selection.Range;
// this is hyperlinked correctly
mso.Hyperlink hl = document.Hyperlinks.Add(range, "http://example.com?id=", ref missing, ref missing, "textToDisplay", ref missing);
// this mergfield is outside of hyperlink
mso.MailMerge merge = app.ActiveDocument.MailMerge;
mso.MailMergeField mf = merge.Fields.Add(range, "id");
// inserts mergefield code into hyperlink, but not as recognizable code by word application
mso.Hyperlink hl2 = document.Hyperlinks.Add(range, "http://example.com?id=" + mf.Code.Text, ref missing, ref missing, "textToDisplay", ref missing);
}
}
Any help would be much appreciated.
UPDATE:
To clarify what result is expected in word document;
I want this: {HYPERLINK "http://example.com?id={MERGEFILED ID}"}
But I get this with the above function: {HYPERLINK "http://example.com?id="}{MERGEFILED ID}
Try this:
string myLink = "http://example.com?id=" + mf.Code.Text;
mso.Hyperlink hl2 = document.Hyperlinks.Add(range, myString, ref missing, ref missing, "textToDisplay", ref missing);
This might be a red herring, but have you noticed it says MERGEFILED and not MERGEFIELD?
I only bring it up because it's in all instances you mention it.

Categories