Welcome message when excel opens using OpenXML in c# - c#

Hi I am creating an excel file through Openxml 2.5 SDK in c#. What i need to do is show a Welcome message in alert pop up.
I have used some ideas like SheetProtection which works when file opens but didn't get the actual solution.
Do any one have something useful. I am digging since last two days on it.
SheetProtection sheetProt = new SheetProtection()
{
Sheet = true,
Objects = true,
Scenarios = true,
Password = "Password"
};
worksheetPart1.Worksheet.InsertAfter(sheetProt, worksheetPart1.Worksheet.Descendants<SheetData>().LastOrDefault());
worksheetPart1.Worksheet.Save();
This is the code we use for password protection and i need which work like this.

Related

Ignore Failing Macro when Opening Excel File with C# Interop

I have been asked to write a script to crawl through a load of folder locations and list out all the Excel spreadsheets that have connections to a set of SQL and other data sources that are due to be upgraded to a new server.
In order to do this, I need to open each file, then check the connections and return those that match the criterion set. All this happens fine until I hit any file where the end user has made a macro to run on open that refers to a non-existent file - As the C# script opens the file, the file presents the following message:
If I manually click "End", the script moves on to the next file and all is ok, but I would much rather avoid any user input and record the fact that there was a problem with the macro... How would I go about doing that?
I have set the Excel property "Disable all macros without notification" to true on the computer that will be running the script, using the same username as will run it, which I thought would prevent this kind of thing happening. I also open Excel with DisplayAlerts=false, so that isn't the problem...
I don't need to run the macro at all and would rather not..!
for context, the code snippet that opens each file looks like this:
var app = new Application
{
Visible = false,
DisplayAlerts = false,
ScreenUpdating = false
};
Workbook thisFile = null;
try
{
//send a false password to stop Excel asking for one - when it is wrong, the error will be caught.
thisFile = app.Workbooks.Open(file.FullName, ReadOnly: true, Password: "FakePassword");
foreach (WorkbookConnection connection in thisFile.Connections)
{
EDIT: It occurs to me that maybe I could do something with a timeout..? If there were some way to close the popup box from the script, that would do the job - I could just record that the timer expired in the output, which would be enough. So... alternatively is there a way to just close the box after it has popped up?
I have been able to disable startup macros when I open the workbook by holding down shift when opening the file.
I believe the interop way to handle this is to use the application AutomationSecurity property:
Excel.Application app = new Excel.Application();
app.Visible = true;
app.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable;
I tested this on a simple workbook that popped up a message box and put the current time in A1, and it seemed to work properly.
Excel.Workbook wb = app.Workbooks.Open("c:/cdh/foot.xlsm");
Default, the message box popped up and A1 had a value, and when I set it to disable neither happened.

MSProject Add-In to convert .mpp in .pdf with given name and date

I am developing an Add-In for MSProject 2013 and higher.
I want to safe/convert the opened .mpp file into an .pdf file without having an additional dialog for the user. He just presses the button an gets an notification when everything is done.
I need to save it in a spacific path and user a defined start and end date.
I tried the SaveAs-methode, but since it takes an MSProject.PjFileType as input and the is no option for pdf, I can't use this. PjFileFormat Enumeration
An other approche was using the DocumentExport-methode.
app.DocumentExport(#"D:/doc_exportqwre.pdf", MSProject.PjDocExportType.pjPDF, true, true, false, System.DateTime.Now, System.DateTime.Now.AddDays(42));
But in this case i only see 3 weeks at once. It is zoomed in and haven't found a way to change this. Changing the View in MSProject, before exporting does not help.
A third way is using the Windows10 pdf-printer:
// generate a file name as the current date/time in unix timestamp format
string file = (string)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds.ToString();
// the directory to store the output.
string directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// initialize PrintDocument object
PrintDocument doc = new PrintDocument()
{
PrinterSettings = new PrinterSettings()
{
// set the printer to 'Microsoft Print to PDF'
PrinterName = "Microsoft Print to PDF",
// tell the object this document will print to file
PrintToFile = true,
// set the filename to whatever you like (full path)
PrintFileName = Path.Combine(directory, file + ".pdf"),
}
};
doc.Print();
but this way I can not give the starting and end date. This results in having way to many pages I do not need.
Is there any chance to achieve my goal with changing one of my solutions or is there any other option?
After not finding a proper solution, i used the windows 10 Printer and simulated keyboard events to insert the path in the dialog, which opens. With Enter i start the printing.
I know it is not a nice solution, but it is the onlyway i got it to work

How to add conditional formatting with EPPlus for Excel 2010

I am using Epplus library to add conditional formatting to an existing Excel spreadsheet with the following code:
var conditionalFormatting = worksheet.Cells[address].ConditionalFormatting.AddExpression();
conditionalFormatting.Formula = $"=IF(EXACT(A1, \"\"), IF(EXACT(B1, \"\"), TRUE, FALSE), FALSE)";
conditionalFormatting.Style.Fill.BackgroundColor = errorColor;
This code seems to be working fine since when I open the spreadsheet with Excel 2016 I can see the appropriate behaviour.
My Question
On opening the same spreadsheet with Excel 2010, I get this message:
Excel found unreadable content in 'Spreadsheet.xlsx'. Do you want to recover the contents of this Workbook?
Recovering the contents: Excel prompts with:
Removed Feature: Conditional formatting from /xl/worksheets/sheet1.xml part
Did this ever happen to anyone else? I think EPPlus library should work fine with Excel 2007+
Does anyone know of any workaround?
Try removing the = sign from the Formula.
conditionalFormatting.Formula = $"IF(EXACT(A1, \"\"), IF(EXACT(B1, \"\"), TRUE, FALSE), FALSE)";
By adding the = it would result in the formula to be shown as ==IF(EXACT... which is invalid. Formulas for conditional formatting are not stored with the beginning = sign. If this still works in Excel 2016, maybe it accepts/ignores the extra =?

Getting 'Compile error in hidden module: SmartTagsMod' while opening a word document in MS Word 2010

I am converting a large number of MS Word documents to PDFs using the Interop library in a multi-threaded WPF application (.NET Framework 4). I get the following error on some word documents:
It blocks the current thread until I click OK on the dialog and then continues with the conversion and the converted PDF comes out to be fine as well.
This only happens on certain documents. I am running the application on multiple computers and this has occured on other computers too.
Below is my code for conversion:
var wordApplication = new Microsoft.Office.Interop.Word.Application();
// Opening the word document
var wordDocument = wordApplication.Documents.Open(tempFile, false, true, false, NoEncodingDialog: false);
// Exporting the document to the PDF
wordDocument.ExportAsFixedFormat(pdfPath, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
// Closing the document and the application.
((Microsoft.Office.Interop.Word._Document)wordDocument).Close(false);
((Microsoft.Office.Interop.Word._Application)wordApplication).Quit(false);
Marshal.ReleaseComObject(wordDocument);
Marshal.ReleaseComObject(wordApplication);
wordDocument = null;
wordApplication = null;
Does anyone know what could be causing this? Or whether I can close this dialog box from my application?
Thanks
wordApplication.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable;
This seem to have fixed the issue.
Thanks bibadia for providing the link to the question that had the fix.

How can I edit or unprotect a single cell in a protected Excel sheet from C#?

I'm trying to manipulate an excel file with C# by using Microsoft.Office.Interop.Excel.
The workbook I'm trying to manipulate has shared protection between users.
I have the file password and I have the password of the cells which I want to access and edit.
If I try to do that from Excel, I do the following:
open the file, type the password
go to a cell, double click on a cell to edit.
a dialogue appears, asking me to provide the password, I provide the password and then I can edit.
I want to do this from a C# application.
My current code is as following:
xl.Application excelApp = new xl.Application();
excelApp.Visible = true;
xl.Workbook newworkbook =
excelApp.Workbooks.Open(#"C:\1.xls", 0, false, 5, "password", "", false,
xl.XlPlatform.xlWindows, "", true, false, 0, true,
false, false);
xl.Sheets excelSheets = newworkbook.Worksheets;
xl.Worksheet excelWorksheet = (xl.Worksheet)excelSheets.get_Item("Sign On_Off");
excelWorksheet.Select(true);
xl.Range myrange = excelWorksheet.get_Range("b16", "b16");
myrange.Value2 = "testing";
The last line gives me this error message:
The cell or chart that you are trying to change is protected and therefore read-only.
I can't unprotect the whole sheet cause that would mean I will have the file opened exclusively for me only and other users can't save changes.
So my question: Is is there is way I can unprotect a cell only?
I imagine something like:
myrange.unprotect("pw");
Protect is just available to Workbook and Worksheet classes.
Alternatively, you can try to work with Worksheet.Protection Property:
ActiveSheet.Protection.AllowEditRanges.Add _
Title:="Range123", Range:=Range("K4:L10"), Password:="123"
I haven't had time to try it, but this paragraph looks like what you are looking for. It seems that the VBA equivalent object you are looking for is ActiveSheet.Protection.AllowEditRanges, which stores information about the areas that can be edited by users in a sheet.
One thing you might want to look into as well is the UserInterfaceOnly option on ActiveSheet.Protect. You can protect a range with a password for users, but access it without password through macros.

Categories