Reading Excel File! Always appear an dialog ask for save - c#

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.

Related

how to input content to a cell without create a new excel document?

now I am working on a project using c# to built a console application, which is to add more functions based on Excel. For example, SUM() is already built in the Excel. I try to add other functions that could work as the same way as SUM().(once the user click on the function button, the function will showed in the excel's active cell with parameters that need to be passed. If user click on like cell B1:A1, the content in B1:A1 will show as one of the parameters in this function. Just work exactly same as how SUM() function work in excel). My question is, if there is a way that I could input the function into the cell without creating a new worksheet. Every time I run the program, it will show a excel itself. And all the function will showed in this excel. So I don't want to create another excel, instead I want to use this excel to achieve all the functions.
this is what I get:
//export is a button, user could click on this button, and the corresponding function should show in the cell. (should in the active cell, but I will figure it out later).
//this give me a new worksheet
//because every time I run the program, the program showed me a worksheet. I want to use this worksheet.
private void export_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)xla.ActiveSheet;
xla.Visible = true;
//index from 1
ws.Cells[2, 1] = trans1.Text;
ws.Cells[3, 1] = trans2.Text;
ws.Cells[4, 1] = trans3.Text;
}
I don't know if I express my question clearly. My English is not that good, but feel free to ask me.
very appreciate for helps!
I get it! it is really easy.
Excel.Application xlapp = (Excel.Application)ExcelDnaUtil.Application;
Excel.Workbook wbook = xlapp.ActiveWorkbook;
Excel.Worksheet wsheet = wbook.ActiveSheet;

Open Excel workbook in background using interop

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)

Excel Interop's set_value method damages values

I found a problem while using the set_value method. I wrote the simplest possible code to exclude my mistakes.
When I read some cells and then write them back to sheet using set_value while:
any filters are active in xlsx file,
2 or more columns are get/set,
some of the cells are corrupted (they are empty or contain junk like #N/D!). When I disable filtering in worksheet or in program before using set_value, everything works fine. I can't find any info about this specific problem in google, am I doing something really stupid?
Excel.Workbooks workbooks;
Excel.Workbook workbook = null;
Excel.Worksheet sheet = null;
Excel.Application excelApplication;
excelApplication = new Excel.Application();
excelApplication.Visible = false;
workbooks = excelApplication.Workbooks;
workbook = workbooks.OpenXML(file);
sheet = workbook.Sheets[1];
Excel.Range excelRangeR = sheet.UsedRange;
object[,] valueArrayR = (object[,])excelRangeR.get_Value(Excel.XlRangeValueDataType.xlRangeValueDefault);
//if uncomment line below (or manualy disable filters in XLSX file), set_value works fine
//sheet.AutoFilterMode = false;
excelRangeR.set_Value(Excel.XlRangeValueDataType.xlRangeValueDefault, valueArrayR);
workbook.Save();
workbook.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelRangeR);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
excelApplication.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApplication);
You can leave the filters on, but if there is an active filter on the sheet, that has to be removed before setting the value of the cells. I think what is happening is that when you set the object[,] variable, it's populating the array with all the data in the range, including the rows that are not visible, but when you set the value of the range to the object[,] array, it only overwrites the visible rows. It's either that or vice versa.
Sorry if this code is incorrect. I'm just guessing at the C# Interop syntax. I don't use it all that often.
if (sheet.get_FilterMode()) {
sheet.ShowAllData();
}
Unfortunately there isn't an easy way to save the current value of the worksheet filters, so it would be difficult if you need to be able to restore the filters after the paste operation.

How to Save/Overwrite existing Excel file with Excel Interop - C#

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);
}

Saving Excel Spreadsheet using Interop C#

static void Main()
{
Application excelapp = new Application();
Workbook book = excelapp.Workbooks.Open(#"C:\HWYFAB.xlsx",
0, false, 5, "", "", false, XlPlatform.xlWindows , "",
true, false, 0, true, false, false);
Worksheet sheet = (Worksheet)book.Sheets[1];
Range cell = (Range)sheet.Cells[3, 2];
Console.WriteLine(cell.Text);
cell.ClearContents();
book.Close(true, "HWYFAB.xlsx", false);
excelapp.Quit();
}
This program runs and exits as expected. It does print the correct value that's in cell B3 to the console. When closing it asks if I want to replace the existing file. I click yes. When I open the spreadsheet in Excel, the value is still in cell B3 despite the cell.ClearContents().
Any thoughts?
Your call to cell.ClearContents() will clear formulas and value constants from the cell. This should absolutely be working. You can confirm this after your call to cell.ClearContents() by testing if cell.Value2 == null, which should be true.
I believe that the problem with your code is in the call to book.Close(true, "HWYFAB.xlsx", false). The problem is that you are explicitly passing in the name of your workbook, but you are leaving off the path. (Note that when you open the workbook you are including the full path, including the "C:\" directory.) By leaving off the full path to the workbook when you save, you are saving to the current directory, which could be "My Documents" or anywhere else.
If you wish to save the workbook in-place, at its original location, then you should pass in Type.Missing for the Filename parameter. For example:
book.Close(true, Type.Missing, false);
This idea is untested, but I'm fairly confident that this should work for you. Give it a try...
-- Mike

Categories

Resources