Check if a specific word document is Open using c# - c#

Is there any way to check if a specific word document is Open? When I open document myself before opening the app when I tell to my app to write something in document first try to open the document and thats where my app is stuck.Is there a way to check before I try to open if the file is already opened? at this moment my code looks like this:
object filename = s; // s is a string path which I get from database
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc1 = app.Documents.Open(s);
object missing = System.Reflection.Missing.Value;
app.Visible = true;

just put your code in a
try
{
//your code here
}
catch (Exception e)
{
//your behavior when the file is opened
}

Related

C# .Net - Insert text in Bookmark without opening Word

I managed to insert a text in a Bookmark of a Word document using Microsoft.Office.Interop.Word.
using Microsoft.Office.Interop.Word;
using Application = Microsoft.Office.Interop.Word.Application;
using Range = Microsoft.Office.Interop.Word.Range;
Application app = new Microsoft.Office.Interop.Word.Application();
Document doc = app.Documents.Open(#"C:\wordDocument.docx");
string bookmark = "bookmarkName";
Bookmark bm = doc.Bookmarks[bookmark];
Range range = bm.Range;
range.Text = "Hello World";
doc.Bookmarks.Add(bookmark, range);
/* OR
doc.Bookmarks[bookmark].Select();
app.Selection.TypeText("Hello");
*/
The problem is this also opened the Word document. Can this be done without opening the document itself? Like its all happening in the background?
Try using the Save and Close function after updating the text of the Bookmark of your Word Document.
Add the below code after the doc.Bookmarks.Add(bookmark, range);.
doc.Save();
doc.Close();
EDIT:
If the computer is slow, the Word document might show within a second since you open it up. As hardcoregamer said, you can try to hide the object of Word.Application first before opening it.
using Microsoft.Office.Interop.Word;
using Application = Microsoft.Office.Interop.Word.Application;
using Range = Microsoft.Office.Interop.Word.Range;
Application app = new Microsoft.Office.Interop.Word.Application();
app.Visible = false; //Hide the Word.Application object.
Document doc = app.Documents.Open(#"C:\wordDocument.docx");
string bookmark = "bookmarkName";
Bookmark bm = doc.Bookmarks[bookmark];
Range range = bm.Range;
range.Text = "Hello World";
doc.Bookmarks.Add(bookmark, range);
doc.Save(); //save the document.
doc.Close(); //close the document.
app.Quit(); //close the Word.Application object. otherwise, you'll get a ReadOnly error later.

save a mailmerge document

I need to produce and save a MS Word .doc file starting from a template (let's say C:\template.doc) and a datasource (let'say C:\datasource.doc)
I'm using MailMerge.Execute and if I let Word to be visible, I see the correct result file, but I can't realize to save this file in any way. The code is:
Microsoft.Office.Interop.Word.Application myWord = new Microsoft.Office.Interop.Word.Application();
Object oFalse = false; Object oTrue = true; Object oFileName = #"C:\merged.doc";
Word.Document myMailMergeDoc = myWord.Documents.Open(#"C:\template.doc");
myMailMergeDoc.MailMerge.OpenDataSource(Name: #"C:\datasource.doc");
myMailMergeDoc.MailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument;
myMailMergeDoc.MailMerge.Execute(oFalse);
try
{
myWord.Documents["template.doc"].Close(oFalse);
myWord.Documents.Save(oFileName);
myMailMergeDoc.SaveAs(oFileName);
myWord.ActiveDocument.SaveAs(oFileName);
}
catch(System.Runtime.InteropServices.COMException ex)
{ }
None of the three saving methods in the try block saves the file on the disk. What am I doing wrong?
Ok, I did it: I missed to install VBA features from Office setup, now the document is correctly saved

Word Export ASP.NET MVC Beginner

i'm new to ASP.NET MVC and tried to generate an export from Formdata to word file. That worked quite well, all the Bookmarks in the Document are filled correctly with following code:
string savePath = (#"U:\Coding ASP.MVC\WebForm Export into WordFile\Gutachten.docx");
string templatePath = (#"U:\Coding ASP.MVC\WebForm Export into WordFile\wordTemplate.docx");
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
doc = app.Documents.Open(templatePath);
doc.Activate();
if (doc.Bookmarks.Exists("FileNoSIS"))
{
doc.Bookmarks["FileNoSIS"].Range.Text = FileNoSIS;
}
if (doc.Bookmarks.Exists("NameOfAction"))
{
doc.Bookmarks["NameOfAction"].Range.Text = NameOfAction;
}
doc.SaveAs2(savePath);
app.Application.Quit();
Response.Write("Success");
But now i want to get the thing done with a stream to edit the document and offer the new filled document as a download. Can anybody here give me some advice or any tip how to get there?
Thx

C# Save duplicate of Active document, but include track changes

I'm working on Word 2010 plugin and I want to copy active document with track changes (http://office.microsoft.com/en-001/word-help/turn-track-changes-on-or-off-HA010370561.aspx) to XML format and later to send it somewhere else.
This is my code:
Microsoft.Office.Interop.Word.Document documentNew = new Microsoft.Office.Interop.Word.Document();
object missing = Type.Missing;
document.Range(ref missing, ref missing).Copy();
documentNew.Range(ref missing, ref missing).PasteAndFormat(Microsoft.Office.Interop.Word.WdRecoveryType.wdFormatOriginalFormatting);
Object xmlFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXML;
documentNew.SaveAs2(file, xmlFormat);
This works, but does not include track changes in duplicate document. Anybody have idea how to also include changes?
How about saving document to the new document in XML first, then opening up the new document and make whatever changes are required? I've tested this approach and it preserves the tracked changed without having to do anything special.
Copy and pasting into a new document is not going to preserve the original tracked changes.
So the code would be:
public static void SaveAsXMLAndDoSomethingElse() {
String fn = #"C:\Users\zbook\Desktop\Track test.docx";
String fn_xml = #"C:\Users\zbook\Desktop\Track test3.xml";
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Documents docs = app.Documents;
Document doc = docs.Open(fn, ReadOnly:true);
//bool b = doc.TrackFormatting; // for some reason this line bombs
doc.SaveAs2(fn_xml, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXML);
doc.Close(false);
Marshal.ReleaseComObject(doc);
// now open up fn_xml ... and do whatever
app.Quit(false);
Marshal.ReleaseComObject(docs);
Marshal.ReleaseComObject(app);
}

Save excel file using savefiledialog class in C#

I need to create and save a Excel file without inform in the code the path and file name. So I can use the savefiledialog to show the save box to input the path and file name, but I can´t use it correctly.
I tried to use the worksheet.saveas but this class doesn´t show the save box to input the path and file name.
How can I save a excel file with that save box?
The basic mechanic of it is this:
public void SaveExcelWorkBook()
{
OpenFileDialog openDlg = new OpenFileDialog();
openDlg.InitialDirectory = #"C:\";
openDlg.ShowDialog();
string path = openDlg.FileName;
if (openDlg.ShowDialog() == DialogResult.OK)
{
try
{
Application excelApp = new Application();
Workbook workBook = excelApp.Workbooks.Open(path);
Worksheet workSheet = (Worksheet)workBook.Worksheets[1];
// Do your work here inbetween the declaration of your workbook/worksheet
// and the save action below.
workBook.SaveAs(/*path to save it to*/); // NOTE: You can use 'Save()' or 'SaveAs()'
workBook.Close();
}
catch (Exception ex)
{
}
}
}
I think I should also mention that Interop objects are unmanaged so, you will want to make sure that you are releasing them after calling .Close(). Here is an example:
Marshal.ReleaseComObject(workBook);
There are two fantastic tutorials for using Excel here and here. Good luck!

Categories