I am using Ms Office Interop assemblies to create a MS Project file. To save the file created, I am using FileSaveAs method and it prompts a message saying that if you want to replace the existing file.
I want to suppress the message, and I didn't find any parameter in FileSaveAs method for this purpose.
Any Idea on this?
I'am using C# as my programming language.
I ran into this issue when working with Excel Interop. The best I've been able to find is to disable all Office alerts, like this:
Microsoft.Office.Interop.MSProject.Application msProjectApp = new Microsoft.Office.Interop.MSProject.Application();
msProjectApp.DisplayAlerts = false;
Never double dot COM objects, as they will not be released and this will leave excel open on your server. Unfortunately I have crashed servers because of this.
private void InitialiseExcel()
{
if (excelApp == null)
excelApp = new Excel.Application();
// Turn off User Prompts
excelApp.DisplayAlerts = false;
// Turn off screen updating so we do not get flicker
var app = excelApp.Application;
app.ScreenUpdating = false;
// Specifies the state of the window;
excelApp.WindowState = Excel.XlWindowState.xlMinimized;
Marshal.ReleaseComObject(app);
}
Related
I use to Open Excel files from my C# Interop application.
However, I cannot pick up (or get connected to) Excel file, when it is already "in air" - open manualy.
app = new Excel.Application();
foreach(var w in app.Workbooks)
{
if(w.name == "MyFile") found = true; //never ever found
}
Could you please advice How To get connected to MyFile.xlsx, not just Open it?
I need to convert a PowerPoint (ppt/pptx) file to PDF using C#
Currently, I'm using this code:
public void PPTXToPDF(string originalPptPath, string pdfPath) {
// Create COM Objects
Microsoft.Office.Interop.PowerPoint.Application pptApplication = null;
Microsoft.Office.Interop.PowerPoint.Presentation pptPresentation = null;
try {
object unknownType = Type.Missing;
//start power point
pptApplication = new Microsoft.Office.Interop.PowerPoint.Application();
//open powerpoint document
pptPresentation = pptApplication.Presentations.Open(originalPptPath,
Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue,
Microsoft.Office.Core.MsoTriState.msoFalse);
// save PowerPoint as PDF
pptPresentation.ExportAsFixedFormat(pdfPath,
Microsoft.Office.Interop.PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF,
Microsoft.Office.Interop.PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentPrint,
MsoTriState.msoFalse, Microsoft.Office.Interop.PowerPoint.PpPrintHandoutOrder.ppPrintHandoutVerticalFirst,
Microsoft.Office.Interop.PowerPoint.PpPrintOutputType.ppPrintOutputSlides, MsoTriState.msoFalse, null,
Microsoft.Office.Interop.PowerPoint.PpPrintRangeType.ppPrintAll, string.Empty, true, true, true,
true, false, unknownType);
} finally {
// Close and release the Document object.
if (pptPresentation != null) {
pptPresentation.Close();
pptPresentation = null;
}
// Quit PowerPoint and release the ApplicationClass object.
if(pptApplication != null) {
pptApplication.Quit();
pptApplication = null;
}
}
}
This snippet uses the Interop libraries, which create an instance of the PowerPoint application and use it programmatically.
The problem is that the application randomly crashes.
Sometimes in the finally block, pptApplication comes null, which means that the application didn't even open, sometimes it says The message filter indicated that the application is busy, sometimes I see a dialog titled "Exporting..." with a progressbar showing the export progress, then the dialog disappears and the program hangs forever until I force-close it.
The application fails randomly with the same file: I run it once, it works, I run it again, it works, I run it again, it doesn't work, etc...
I cannot have an application that sometimes works and sometimes fails, so my question is: Is there a reliable alternative for converting PowerPoint files to PDF which doesn't use Interop? Did Microsoft provide an alternative API to do these things without opening an instance of PowerPoint?
The reason why I'm using Interop at the moment is that I also have to read the PowerPoint file and search for shapes in slides, if that matters.
UPDATE
The PC I'm running my application is a Windows 7 PC with Office installed. I cannot install anything else, that's why I need to find an independent library.
Only other way that comes to my mind is try using libreoffice for the same task. It has headless mode (no UI) and can be called from command line, like this:
"C:\Program Files (x86)\LibreOffice 5\program\soffice.exe" --headless --convert-to pdf:writer_pdf_Export test.pptx
Note that it will exit immeditaly (because it is designed for batched processing), but you can watch output directory using FileSystemWatcher and when desired file was created there (and when you are able to acquire exclusive lock on it) - it is done. You can also do batch processing with it, for more options available look here - https://help.libreoffice.org/Common/Starting_the_Software_With_Parameters. I used it for some conversions and had no problems doing that.
Using interop you can try to generate the pdf using this approach:
I have tested making fifty exports at one time and worked fine.
_oPresentation.SaveAs(outputFullPath,
PowerPoint.PpSaveAsFileType.ppSaveAsPDF,
Microsoft.Office.Core.MsoTriState.msoCTrue);
Note: _oPresentation is just the interop presentation instance (Microsoft.Office.Interop.PowerPoint.Presentation).
I am creating a command line application and I would like to connect to a SharePoint site that has a workbook that I want to update.
I don't even know where to start but I guess the questions I have are.
What API can I use for this? It has to be something that is already built-in and not a third party API if possible :)
Once the connection is done and I am able to open the spreadsheet, will I be able to also switch from one sheet to another?
I've tried to use some code like this but it did not work.
private static void GetExcelSheetNames(string filename)
{
var xls = new Microsoft.Office.Interop.Excel.Application();
xls.Visible = true;
xls.DisplayAlerts = false;
var workbook = xls.Workbooks.Open(Filename: filename, IgnoreReadOnlyRecommended: true, ReadOnly: false);
try
{
// Refresh the data from data connections
workbook.RefreshAll();
// Wait for the refresh occurs - *wish there was a better way than this.
System.Threading.Thread.Sleep(5000);
// Save the workbook back again
workbook.SaveAs(Filename: filename); // This is when the Exception is thrown
// Close the workbook
workbook.Close(SaveChanges: false);
}
catch (Exception ex)
{
//Exception message is "Cannot save as that name. Document was opened as read-only."
}
finally
{
xls.Application.Quit();
xls = null;
}
}
The Exception that I get was:
Microsoft Excel cannot access the file 'https//url/bla/bla/bla/workbook.xlsx There are several possible reasons:
The file name or path does not exist.
The file is being used by another program.
The workbook you are trying to save has the same name as a currently open workbook.
Actually, it seems like it is trying to open an instance of Excel Desktop in my machine.
Sorry for such an open question but I don't really know how can I connect to a SharePoint site.
Thanks in advance!
If you're using a document in a document library, check to make sure that it is checking out the document before you try to save it. I am working with a similar process but using a report library instead of a document library and am able to save documents without check out/in.
I'm working on excel using C#, but I face some issues while insert picture comments into excel.
Here is my code:
public void InstertPictureComment(Excel.Range myrange, string picturepath)
{
myrange.ClearComment();
myrange.AddComment();
myrange.Comment.Shape.Fill.UserPicture(picturepath);
myrange.Comment.Shape.Width=400;
myrange.Comment.Shapes.Height=300;
}
The above code works well and I can succesfully insert picture comments.
However, issues show up.
Copy the contents (with the picture comments I have just inserted) to other excel worksheet
==>save excel, and close excel app
==> reopen excel, and a messagebox telling "Excel found unreadable content in xxxxx"
What's wrong with my code? Or it's an excel issue?
I have corrected the code so that it compiles
public void InstertPictureComment(Excel.Range myrange, string picturepath)
{
myrange.Cells.ClearComments();
myrange.AddComment();
myrange.Comment.Shape.Fill.UserPicture(picturepath);
myrange.Comment.Shape.Width = 400;
myrange.Comment.Shape.Height = 300;
}
Part of the problem is with Excel. With your code, you are probably creating a new application instance of Excel. Excel is unable to copy objects across the application instances.
If you open another workbook in the same application instance, the objects will get copied. The only way to copy data across application instances is using Paste Special functionality.
You should fetch the existing Excel application instance. If it is not there, then you may create it.
private Excel.Application GetExcelInstance()
{
Excel.Application instance = null;
try
{
instance = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
}
catch (System.Runtime.InteropServices.COMException ex)
{
instance = new Excel.Application();
appCreatedExcelInstance = true;
}
return instance;
}
You may use the appCreatedExcelInstance flag to decide whether or not to quit the instance during cleanup.
Is there a way to save changes to an excel spreadsheet through the excel interop (in this case I am adding a worksheet to it) without having it prompt the user if they want to overwrite the existing file with the changes. I do not want the user to even see the spreadsheet open in my application so having a message box popping up asking them if they want to overwrite the file seems very out of place and possibly confusing to the user.
I am using the workbook.SaveAs(fileloaction) method.
Here is where I am initializing the COM reference objects for the excel interop.
private Excel.Application app = null;
private Excel.Workbook workbook = null;
public Excel.Workbook Workbook
{
get { return workbook; }
set { workbook = value; }
}
private Excel.Worksheet worksheet = null;
private Excel.Range workSheet_range = null;
Below is the code I am using to close/save the excel file. The workbook.close() method line is the one that is reportedly throwing the unhandled exception.
workbook.Close(true, startForm.excelFileLocation, Missing.Value);
Marshal.ReleaseComObject(app);
app = null;
System.GC.Collect();
Basically, all you need is ExcelApp.DisplayAlerts = False - Here's how I do it, though:
ExcelApp.DisplayAlerts = False
ExcelWorkbook.Close(SaveChanges:=True, Filename:=CurDir & FileToSave)
Hope this helps
Only this code will Require for stop override alert or Template already in use
ExcelApp.DisplayAlerts = False
I know this is an old post, but I wanted to share a way to make this work without causing possible frustration in the future.
First what I do not like about using: ExcelApp.DisplayAlerts = False
Setting this flag will set this property on the excel file, not just in your program. This means that if a user makes changes to the file and closes it (by clicking the X), they will not be prompted to save the file and will cause frustration later. It will also disable any other prompts excel would typically post.
I like checking if the file exists before saving it:
if (File.Exists(SaveAsName))
{
File.Delete(SaveAsName);
}