Let me first describe the problem. I have this application that opens a word document and updates all the fields and then saves the document in another folder. The word document is just used as a template for a report. It is filled with linked content from an excel worksheet. The whole application works, but the problem is that the excel document is password protected. when I update the document fields the application is stopped and word asks for a password.
When you input the password, the program works as advertised, you have to insert it more than once thou, dont really know why. But the program is suppose to work autonomously without user input. Is there a way to give word the password so that it doesnt have to be entered, either via code or in the word document properties.
Below is my current code that does this, its in C#
Microsoft.Office.Interop.Word.Application ap = new Microsoft.Office.Interop.Word.Application();
Document doc = ap.Documents.Open(template, ReadOnly: false, Visible: false);
doc.Activate();
red_debug.AppendText("opening " + template + "\n");
doc.Fields.UpdateSource();
doc.Fields.Update();
red_debug.AppendText("Saving as " + final + "\n");
doc.SaveAs(final, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument);
doc.SaveAs(path + "\\" + name, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);
red_debug.AppendText("Closing word" + "\n");
doc.Close();
ap.Quit();
Get the Word document to open up the Excel file (with the password) for you everytime it has been opened. Same time, we can also successfully close the Excel file from Word.
Put this into the Word macro area.
Private Sub Document_Open()
Dim xlApp As Object
Dim xlWB As Object
Dim myRange
Application.DisplayAlerts = wdAlertsNone
Set xlApp = CreateObject("Excel.Application")
Set xlWB = xlApp.Workbooks.Open("C:\ExcelFile.xls", , , , "password", "password")
Set myRange = Selection.Range
Selection.WholeStory
Selection.Fields.Update
myRange.Select
xlApp.Quit
Set xlWB = Nothing
Set xlApp = Nothing
Application.DisplayAlerts = wdAlertsAll
End Sub
This will open up the excel document and update ALL fields on your word document and shouldnt ask you for password
I think you can try to call doc.Unprotect(ref Object password) by passing your password as argument.
Check out this article on CodeProject and this on MSDN.
Related
Is there a way of opening password protected Word and Excel files without manually entering password when developing an application or document level VSTO Add-in. In other words, how do I set the password programmatically.
I have tried to do it in the document open event but it is invoked after opening document.
Is there an event which is invoked before the document gets opened?
Basically what I want to achieve is avoid opening the document outside the my Add in
Yes there is - look at documentation here. Basically - you need to pass the password, when opening the document instead of relying on events.
For Word:
var WordApp = new Word.Application();
WordApp.Documents.Open("[your doc path].docx", ReadOnly: false, Password: "[your password]")
For Excel:
var ExcelApp = new Excel.Application();
ExcelApp.Workbooks.Open("[your doc path].xslx", ReadOnly: false, Password: "[your password]")
Is it possible to set the excel filename before file saving?
I have following simple code:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = new Excel.Application();
excel.Visible = true;
Excel.Workbook workbook = excel.Workbooks.Add(Excel.XlSheetType.xlWorksheet);
Excel.Worksheet sheet = workbook.Sheets[1];
sheet.Cells[1, 1] = "Hello World!";
Is it possible to predefine this name before saving?
Thanks.
There is no explicit, foolproof way to do this prior to saving, unfortunately. The closest you could come is to use a template. If you have a template called FOO.xltx, you could create your workbook like this:
Application.Workbooks.Add "X:\path\to\FOO.xltx"
The only quirk is that the name for the new documents will be appended with an incrementing number (FOO1 the first time, then FOO2,FOO3, etc.).
To create a template, just create a new document, and when you save it, select Excel Template (*.xltx) from the Save as type dropdown.
You have to use saveas to save the file with the filename you want. Then when the user clicks save it will just update the file that was previously created. Unfortunately there is no other way. Here is the code:
workbook.SaveAs(Filename: FILENAMEHERE);
Here is the MSDN doc for it: https://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.saveas.aspx
I'm trying to insert a file programmatically (*.zip for example) into an existing docx file.
I looked at the docx open library but it doesn't have the function there.
Also tried using Microsoft.Office.Interop.Word. I created a word document with a table, and I'm trying to insert a file into a cell inside the table.
Word.Application wordApp = new Word.Application();
wordApp.Visible = false;
Word.Document doc = new Word.Document();
doc = wordApp.Documents.Open(Environment.CurrentDirectory + "\\test.docx");
doc.Tables[1].Rows[2].Cells[1].Range.InsertFile((Environment.CurrentDirectory + "\\tttt.zip"));
but it caused an error:
"The file appears to be corrupted"
Can anyone have experience and help with this?
After a lot of trial and error...
The function "Range.InsertFile" doesn't actually inserts a file, it reads and appends the text into the Range.
The solution was simple - Copy paste...
using System.Collections.Specialized;
...
...
//Copy the Filename to Clipboard (setFile function uses StringCollection)
StringCollection collection = new StringCollection();
collection.Add(Environment.CurrentDirectory + "\\MyFile.zip");
Clipboard.SetFileDropList(collection);
//Paste into the selected Range.
range.Paste();
*There is also function "PasteSpecial" which didn't work (Only specific data types are supported).
I am trying to get the name of the workbook before it actually opens up.
((Excel.AppEvents_Event)this.Application).WorkbookOpen += new Excel.AppEvents_WorkbookOpenEventHandler(App_WorkBookOpen);
private void App_WorkBookOpen(Excel.Workbook Wb)
{
System.Windows.Forms.MessageBox.Show("Shakti " + " " + Wb.Name);
}
With the handler as shown above, Excel application shows the workbook name when it is opened completely.My intention is to do some formal check before it is actually opened up and data is shown to the user.
Is there any way or mechanism to extract the file name before the contents are loaded on to Excel and shown to the user? Any sort of help is highly appreciated.Thanks.
AFAIK you can't do that. But like I mentioned in my comment you could hide the workbook the moment it is visible. So the user will see the workbook open for a split second and then go invisible. In that split second you can read the name of the workbook and then hide the workbook.
Based on your calculations/conclusion you can then close/unhide the workbook as required.
You can hide the workbook using
Wb.Windows[1].Visible = false;
No you can't.
You anyway could create a Macro on a WorkBook Module with Open class tag as here:
Private Sub Workbook_Open()
Dim ws As Workbooks
For Each ws In ActiveWorkbook.Worksheets
MsgBox ws.Name
Next
ActiveWorkbook.Worksheets.Close
End Sub
Then call this sub via c# on opening the file, this sub runs before loading the workbook then it closes it. It has not that sense, because you'll never access the wb again...
Maybe with some tweaking here and there you could accomplish your task, but it depends to you.
Hope it helps...
Isn't Wb.name the same as the filename? In which case, since you must know the filename/location in order to open it, you can check it beforehand?
I have looked and failed to find a solution to my problem. I have developed an Add-in ribbon for Word 2007 which provides an additional set of load and save functions, to allow users to load and save documents from a bespoke system.
I have most of it working - when a user requests a file to be opened, it is downloaded and saved to the AppData folder, and then opened. However, the problem I am having is that if the user for example opens Word and uses this new 'load' function, the blank Word document remains, and Word opens the new document quite happily, but it does not get the focus.
(I'm on Windows 7 and it creates a second 'W' icon in the task bar for the new document, but it doesn't switch to it in the same way that Word would if I'd used the normal 'Open' route.)
I have tried (as a result of suggestions found elsewhere on here) either setting the 'visible' attribute to true, and calling doc.Activate() but neither does what I need. What am I missing? The code I'm using to open the file is below:
private void OK_Click(object sender, EventArgs e)
{
this.Close();
FES.FESServices wService = new FES.FESServices();
int request_id = wService.SubmitRequestFromAddIn(username, password, "RETR", "", textBox1.Text, "", "");
FES.FileRequestResponse response = wService.GetFileMembersFromAddIn(username, password, request_id);
if (response.ResponseType == "RETR")
{
byte[] data = wService.GetBytesForFilename(response.ResponseValue);
//MessageBox.Show("Loaded data for file...");
//MessageBox.Show(Application.UserAppDataPath);
FileStream fs = new FileStream(Application.UserAppDataPath + "\\" + response.ResponseValue.Substring(6).Split('~')[0], FileMode.Create, FileAccess.Write);
fs.Write(data, 0, (int)data.Length);
fs.Close();
object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Document doc = Globals.ThisAddIn.Application.Documents.Open(
Application.UserAppDataPath + "\\" + response.ResponseValue.Substring(6).Split('~')[0], Visible:true
);
doc.Activate();
}
}
(I have included this.Close() as the function loading the document is held within a modal dialog box, and without closing it first, Word throws an exception about switching documents with a dialog box open).
Any help gratefully received!
Running this code whilst the modal dialog is showing is interfering with window activation.
I'm not sure exactly what the mechanism is for this interference, but the fix is simple enough. Move the code outside the dialog. Execute this code immediately after the call to ShowDialog returns.