(I'm week in English language, so at first excuse me for bad explaining :D )
I open an excel file through my application.
I have an Addd-In in Excel and a button in ribbon for save (exactly such a save action that Save button do) code of Click event of button is here:
Globals.ThisAddIn.Application.ActiveWorkbook.Save();
In my application I assign a method (called WorkbookBeforeSave) to "BeforeSave" event handler of workbook that save workbook manually in my custom directory.
private void WorkbookBeforeSave(bool saveasui, ref bool cancel)
{
_excelApp.EnableEvents = false;//_excelApp is my Excel Application
if (!_excelWorkbook.Saved)//_excelWorkbook is Active Excel Workbook
{
_excelWorkbook.SaveCopyAs(_savedFilePath);//_savedFilePath is my custom directory
_excelWorkbook.Saved = true;
}
cancel = true;
_excelApp.EnableEvents = true;
}
problem is when I click Original Excel Save Button "SaveCopyAs" method works correctly but when click on my custom Save Button "SaveCopyAs" method does not work.
(no exception has thrown and all of codes compiled and debugged)
Try to debug with try-catch, it should be helpful for you.
// using interop, excel tool, interop-excel, core
public void MyBeforeSave(Microsoft.Office.Interop.Excel.Workbook Wb, bool SaveAsUI, ref bool Cancel)
{
//Globals.ThisAddIn.Application.ActiveWorkbook.SaveCopyAs(filename2); // if u use an external class to save (for threading or something else )
this.Application.ActiveWorkbook.SaveCopyAs(filename);
}
Without threading/tasking the office 2007 excel - sometime - lagging or slower than normal at loading and at the save method.
The simple saveAs() method have lot of parameters (searh for it, you see it on msdn & here too) and its needs some hoak at the path, because the latest save-path change to the C# used save path.
I prefer the SaveCopyAs solution, because just one parameter and fast & furious. :D
Related
I'm trying to open an excel file using a button click. And for some reason it's not working. I've tried several things. Any ideas why they are not working?
Method 1 I have tried. This opens the file manager but does not open the proper file. It is definitely using the proper path to the file and the file does exist
private string fileCopy;
public RepairResultsControl()
{
InitializeComponent();
}
public void Show(PSRepair.AnalysisResults analysis, string pathNameCopy)
{
fileCopy = pathNameCopy;
Show();
}
private void btnGoToFile_Click(object sender, EventArgs e)
{
Process.Start("explorer.exe", "/select,"+ fileCopy);
}
Method 2. This just didn't open anything not sure why
System.Diagnostics.Process.Start(#"C:\Users\username\Documents\newTest.xlsx");
Normally, Process.Start(#"C:\Users\username\Documents\newTest.xlsx"); would open your document in Excel.
However, you say in a comment that you are doing this from an Excel add-in which runs in the background. The solution needs to take this into account (the code sample assumes that you have a VSTO add-in, otherwise you need to adjust accordingly):
// make the running Excel instance visible
Globals.ThisAddIn.Application.Visible = true;
// open the workbook using Excel interop
Globals.ThisAddIn.Application.Workbooks.Open(fileName);
Try running as an admin
Check for exceptions, also the start method should return a bool, check to make sure it is true.
Make SURE your xlsx files are associated with Excel(easy check for this is at a command prompt, type in your filename and hit enter... if excel opens you are good)
Check your system error logs.
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.
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);
}
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);
}