excel file to save value in cell range - c#

protected void Page_Load(object sender, EventArgs e)
{
try
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(#"D:\Tesco\NGC\Output\temp_02Feb2012.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
Worksheet sheet = (Worksheet)wb.Sheets["ExpiredAccount"];
Range excelRange = sheet.UsedRange;
Range rng1 = sheet.get_Range("A2", "A2");
rng1.Value2 = "India";
Range rng2 = sheet.get_Range("A3", "A3");
rng2.Value2 = "Good work";
// string A4D4 = GetRange("A" + 2 + ":A" + 2 + "", sheet);
}
catch (Exception ex)
{
throw ex;
}
}
i am trying to open an excel file and an particular sheet called[ExpiredAccount].where i need to set an value in that particular range
here is my code but its not saving the value only, its not throwing any error.
please let me know where i am going wrong it would great if you can help me on this
Thanks
Prince

you have to save the workbook. and release the runtime callable wrapper.
simply add this code:
wb.Close(true, Type.Missing, Type.Missing); //closes and saves the workbook
app.Quit();
Marshal.FinalReleaseComObject(app); //release the wrapper
p.s. if you weren't releasing the object, I suggest to run the Task manager, check the processes tab, and end all Excel.exe processes... there ought to be a lot of them :)

Related

excel file values are not updating

In my application i have an excel sheet with button. Using C# code i'm calling the button of excel file and the excel file click event also working very fine. I placed msg box in macros in that way i verified the click event of the excel sheet button working fine.But after running the macro the values are not updating in excel sheet. Please refer my code below ,
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook;
xlWorkBook = xlApp.Workbooks.Open("D:test.xlsm", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel.Worksheet xlWorkSheet;
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlApp.Run("Module1.solver", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.Close(false, Type.Missing, Type.Missing);
xlApp.Quit();
releaseObject(xlApp);
releaseObject(xlWorkBook);
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
throw (ex);
obj = null;
}
finally
{
GC.Collect();
}
}
Am I missing some function to update excel file ? And the macros I'm using are
SolverOk SetCell:="$A$6", MaxMinVal:=2, ValueOf:=0, ByChange:="$A$4:$A$6", _
apple:=1, applecurry:="GRG Nonlinear"
MsgBox "$3"
SolverOk SetCell:="$A$6", MaxMinVal:=2, ValueOf:=0, ByChange:="$A$4:$A$6", _
apple:=1, applecurry:="GRG Nonlinear"
MsgBox "$4"
SolverSolve
When you start Excel via automation, any add-ins or items in the xlstart folder are not loaded.
If your code relies on add-ins being loaded, then you will need to load them via your code.
See: https://support.microsoft.com/en-us/kb/213489

Open an excel worksheet [duplicate]

I know we can open a particular worksheet of MS Excel using C# by providing the sheet number (1,2,3..) or name (sheet1, sheet2, sheet3...)
I have a excel file which has 2 sheets, 1. Values, 2. Results
Is there a way to open a sheet giving the sheet name ,i.e, "Values" instead of 1 or [s|S]heet1 in C# ??
I looked thru the old posts but didnt find anything useful...
so again, what I am trying to do is, open a Excel worksheet by using its user defined name (Values) instead of the system defined name(1 or [s|S]heet1)
any inputs would be greatly appreciated!
Add reference to Microsoft.Office.Interop.Excel in your project and you can use next code as base
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = false;
oXL.DisplayAlerts = false; // prevents message from popping up
try
{
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Open(filename, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
int nCounter = 1;
oSheet.Copy(oSheet, Type.Missing);
Excel._Worksheet oSheetGame = (Excel._Worksheet)oWB.Worksheets["MyTemplate"];
oSheetGame.Name = "MyNewWorksheetName";
// do something with worksheet
((Excel._Worksheet)oWB.Sheets["MyTemplate"]).Delete(); // delete template
((Excel._Worksheet)oWB.Worksheets["MyNewWorksheetName"]).Activate();
}
catch (Exception e)
{
//throw e;
throw;
}
finally
{
//Make sure Excel is visible and give the user control
//of Microsoft Excel's lifetime.
oXL.Visible = true;
oXL.UserControl = true;
}
oXL.Save(Type.Missing);
#volody, thanks! your post helped a lot.
I took the worksheet declaration part from yours and changed mine into following:
Excel.Application excelApplication;
Excel.Worksheet excelWorksheet;
Excel.Workbook excelWorkbook;
Excel.Range range;
excelApplication = new Excel.Application();
excelWorkbook = (Excel.Workbook)(excelApplication.Workbooks.Open(
<FILENAME>,
Type.Missing, true, Type.Missing, Type.Missing, Type.Missing,
true, Type.Missing, Type.Missing, false, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing));
excelWorksheet = (Excel.Worksheet)excelWorkbook.Worksheets[<WORKSHEETNAME>];
The code above helps in opening a Excel Worksheet with a User defined name. For example, to open a Worksheet named Test instead of Sheet1.
Ivar

Interop Worksheets printoutEx doesn't print first page

I have an application which generates an excel file. when it is going to be printed by following method, the first page isn't printed.
We pass excel file name as filename and Printer Settings via PrintDialog as printerSettings.
then we use Microsoft.Office.Interop.Excel.Application to open then given file and Microsoft.Office.Interop.Excel.Workbook to open the workbook and print whole sheets via wb.Worksheets.PrintOutEx().
in the case when I select XPS Printer as the printer it gets the output filename two times (the time when is printing the first sheet and the time when it is printing other sheets).
when I changed the printing method calling to wb.Worksheets.PrintOutEx(1,1, ... ) the output file hadn't been created.
public static void PrintWorksheet(string fileName, PrinterSettings printerSettings )
{
Application excelApp = null;//excel application
Microsoft.Office.Interop.Excel.Workbook wb = null;//workbook
try
{
excelApp = new Microsoft.Office.Interop.Excel.Application();//initialize excel app
wb = excelApp.Workbooks.Open(
fileName,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing); //open workbook
wb.Worksheets.PrintOutEx(1, wb.Worksheets.Count, printerSettings.Copies, false, printerSettings.PrinterName, false, printerSettings.Collate, false, Type.Missing);//calling print method
}
catch(Exception e)
{
string err = e.Message;
}
finally
{
//closing the excel app and workbook
GC.Collect();
GC.WaitForPendingFinalizers();
if (wb != null)
{
Marshal.FinalReleaseComObject(wb.Worksheets);
wb.Close(false, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(wb);
}
if (excelApp != null)
{
excelApp.Quit();
Marshal.FinalReleaseComObject(excelApp);
}
}
}
can anybody help me?
Have you tried doing the following method instead NamedRange.PrintOutEx Method
Microsoft.Office.Tools.Excel.NamedRange myNamedRange = Globals.Sheet1.namedRange1;
myNamedRange.PrintOutEx(
1,
wb.Worksheets.Count,
printerSettings.Copies,
false,
printerSettings.PrinterName,
false,
printerSettings.Collate,
false
);

Using Excel InputBox to capture a sheet name in C#

I would like to use an Excel InputBox() to capture the name of a sheet by clicking on it, or it's tab. However, when I use the following code:
Excel.Application _excel = this.Application; // this refers to an C# excel addin.
// ...
var result = _excel.InputBox(
"prompt",
"Sheet Selection",
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
I get the result
"='Sheet Name'!"
but instead what I would like is
"Sheet Name"
I've tried using the InputBox text specifier (2) as mentioned here but this doesn't seem to make any difference. Any ideas what I'm doing wrong?
EDIT
I have found that if I capture a range, I can use it to deduce the sheet name I need:
Excel.Range result = _excel.InputBox(
prompt,
"Sheet Selection",
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing) as Excel.Range;
if (result == null)
return null;
return result.Worksheet.Name;

Opening MS Excel worksheet in C#

I know we can open a particular worksheet of MS Excel using C# by providing the sheet number (1,2,3..) or name (sheet1, sheet2, sheet3...)
I have a excel file which has 2 sheets, 1. Values, 2. Results
Is there a way to open a sheet giving the sheet name ,i.e, "Values" instead of 1 or [s|S]heet1 in C# ??
I looked thru the old posts but didnt find anything useful...
so again, what I am trying to do is, open a Excel worksheet by using its user defined name (Values) instead of the system defined name(1 or [s|S]heet1)
any inputs would be greatly appreciated!
Add reference to Microsoft.Office.Interop.Excel in your project and you can use next code as base
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = false;
oXL.DisplayAlerts = false; // prevents message from popping up
try
{
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Open(filename, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
int nCounter = 1;
oSheet.Copy(oSheet, Type.Missing);
Excel._Worksheet oSheetGame = (Excel._Worksheet)oWB.Worksheets["MyTemplate"];
oSheetGame.Name = "MyNewWorksheetName";
// do something with worksheet
((Excel._Worksheet)oWB.Sheets["MyTemplate"]).Delete(); // delete template
((Excel._Worksheet)oWB.Worksheets["MyNewWorksheetName"]).Activate();
}
catch (Exception e)
{
//throw e;
throw;
}
finally
{
//Make sure Excel is visible and give the user control
//of Microsoft Excel's lifetime.
oXL.Visible = true;
oXL.UserControl = true;
}
oXL.Save(Type.Missing);
#volody, thanks! your post helped a lot.
I took the worksheet declaration part from yours and changed mine into following:
Excel.Application excelApplication;
Excel.Worksheet excelWorksheet;
Excel.Workbook excelWorkbook;
Excel.Range range;
excelApplication = new Excel.Application();
excelWorkbook = (Excel.Workbook)(excelApplication.Workbooks.Open(
<FILENAME>,
Type.Missing, true, Type.Missing, Type.Missing, Type.Missing,
true, Type.Missing, Type.Missing, false, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing));
excelWorksheet = (Excel.Worksheet)excelWorkbook.Worksheets[<WORKSHEETNAME>];
The code above helps in opening a Excel Worksheet with a User defined name. For example, to open a Worksheet named Test instead of Sheet1.
Ivar

Categories