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);
}
Related
It seems that most questions regarding working with Excel files through C# resolve around doing it in a fully automated way. I have a slightly different issue.
The way the code is supposed to work.
Launches a batch that creates a .txt file in given location, populated by results of a sql query. (Done and works)
Opens the file in Excel (the reason why I use .txt is that .csv messes up my numbers by removing leading zeroes etc) and makes it visible to the user. The code stops working and leaves the rest to the user.
User makes the changes to the file himself and manually saves them and exits Excel.
The problem that I am encountering is that the process does not want to 'leave the file alone'. It opens correctly, I edit the value and then I save it and when I try to close it it asks me if I want to save changes again. I click yes and that immediately brings up another popup asking the same question.
I do not know how to 'release' the file so that its control will be fully up to the user without actually closing Excel.
This is the bit of code that I use:
{
(...)
RunBatch("Manual_adjustment");
string fileName = "Manual_Adjustment.txt";
Excel.Application excel = new Excel.Application();
object misValue = System.Reflection.Missing.Value;
Excel.Workbook excelWorkbook;
excel.Visible = true;
excelWorkbook = excel.Workbooks.Open(ConstantValues.FolderPathInput + + #"\" + fileName);
releaseObject(excelWorkbook);
releaseObject(excel);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
How do I let the user save the changes without making him manually open the file from the OS level?
I think calling to Excell.Application.Quit may works
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.
I'm wanting to import data from an Excel workbook without actually displaying the open workbook.
I could have sworn I had used the following code on a previous project and it had worked:
var excelApp = new Excel.Application { Visible = false };
var workbook = excelApp.Workbooks.Open(filePath);
Unfortunately when the workbook opens it is displayed to the user which is unnecessary for this application.
I'm using Microsoft Excel 15.0 Object Library on this project when previously I think it was version 12 or 13. Maybe this is the problem, or is my memory fading and the code is incorrect?
I know this is old but just in case anybody still needs this answer...
excelApp.Visible = false;
(excelApp being the name of the variable used for the excel application)
I'm trying to read data from excel file. My problem is when I finished reading it's always appear an dialog ask for save. How can I turn off it?
Here is my code:
Missing missing = Missing.Value;
Excel.Application _app = new Excel.Application();
Excel.Workbook _workBook = _app.Workbooks.Open(e.Argument.ToString());
Excel.Worksheet _workSheet = _workBook.ActiveSheet;
Excel.Range _range = _workSheet.UsedRange;
BackgroundWorker bw = sender as BackgroundWorker;
for (int i = 0; i < _range.Rows.Count; i++) {
if (_workSheet.Cells[i + 2, 1].Value != null && _workSheet.Cells[i + 2, 2].Value != null)
{
inputList.Add(new infoInput(_workSheet.Cells[i + 2, 1].Value, _workSheet.Cells[i + 2, 1].Value));
}
bw.ReportProgress(((i + 1) * 100)/_workSheet.UsedRange.Rows.Count);
}
_workBook.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(_workBook);
_app.DisplayAlerts = false;
_app.Quit();
P/S Sorry for my English! Thanks in advance.
You should set the DisplayAlerts property to FALSE to prevent this message when you call .Quit() method.
_app.DisplayAlerts = false;
_app.Quit();
_Application.Quit method:
If unsaved workbooks are open when you use this method, Microsoft
Excel displays a dialog box asking whether you want to save the
changes. You can prevent this by saving all workbooks before using the
Quit method or by setting the DisplayAlerts property to False. When
this property is False, Microsoft Excel doesn’t display the dialog box
when you quit with unsaved workbooks; it quits without saving them.
have you tried something like this
_workBook.Close(SaveChanges:false)
or
WB.Close(false, Type.Missing, Type.Missing);
according to this link:
http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.close.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
if you omit this parameter, a save dialog will appear.
If there are no changes to the workbook, this argument is ignored. If
there are changes to the workbook and the workbook appears in other
open windows, this argument is ignored. If there are changes to the
workbook but the workbook does not appear in any other open windows,
this argument specifies whether changes should be saved, as shown in
the following list.
true. Saves the changes to the workbook. If there is not yet a file
name associated with the workbook, then FileName is used. If FileName
is omitted, the user is asked to supply a file name.
false. Does not save the changes to the workbook.
Omitted. Displays a dialog box asking the user whether or not to save
changes.
I had this same problem. All the suggestions about macros, repairing MS Office, etc. were no help at all -- although they were related to the problem ...
It turns out that I accidentally changed a date in one cell of the spreadsheet from a valid date -- ex: 02/06/2021 -- to the letter "H". I don't know when I did it, but it was not a temporary change -- i.e., I apparently hit Enter or an arrow kay after the change. Interestingly, that cell was NOT linked to any macros or formulas; it just was formatted as a date. When I repaired the date, and saved the spreadsheet, the problem went away for good.