I developed a program that tries to update certain cells of an existing excel sheet. When I try to set the values of certain cells, I can't find my changes applied to the saved excel sheet.
Here is the code of the method that updates the excel sheet cells with certain values:
public static string filePath = #"D:\Egyption Consulate\StatisticalTemplate.xlsx";
public void UpdateExcelTmplate(Dictionary<int,int> source, string ExcelHeader)
{
Application xlApp = new Application();
Workbook xlWorkBook = xlApp.Workbooks.Open(filePath, 0, false, 5, "", "", false,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Worksheet xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);
Range xlRange = xlWorkSheet.UsedRange;
xlWorkSheet.Cells[3, 12] = source[0];
xlWorkSheet.Cells[4, 12] = source[1];
xlWorkSheet.Cells[5, 12] = source[0] + source[1];
xlApp.DisplayAlerts = false;
xlWorkBook.SaveAs(filePath, XlFileFormat.xlOpenXMLWorkbook,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlNoChange,
XlSaveConflictResolution.xlLocalSessionChanges, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
xlWorkBook.Close();
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
MessageBox.Show("Done");
}
I checked all posts on stackoverflow and they are using the same way i'm using but my issue that cells' values are not updated. Does anyone know what is the reason behind that issue?
I know the issue now. There was a lock on the excel file in addition to that I used incorrect index of excel row and column.
I have a C# web form, that a user enters a part numbers and a quantity on, then selects a button. Ideally, I want to search the excel file for the part that was entered, then add the quantity specified by the user.
The excel file is a static list of all parts that can be entered. I'm just testing the code, so for testing I'm just changing the color of the text and making it bold if its found...
Now, I'm getting the error...
"'HttpApplicationState' does not contain a definition for 'get_Range' and no extension method 'get_Range' accepting a first argument of type 'HttpApplicationState' could be found (are you missing a using directive or an assembly reference?) CSMP_Bid_Registration C:\BPR Projects\CSMP Registration\CSMP_Registration_1_03\CSMP_Bid_Registration\Create.aspx.cs 452 Active"
protected void btnSearchRequest_Click(object sender, EventArgs e)
{
//Microsoft.Office.Interop.Excel.Range currentFind = null;
Microsoft.Office.Interop.Excel.Range firstFind = null;
object False = false;
object True = true;
_Application excel = new Microsoft.Office.Interop.Excel.Application();
String _Created = DateTime.Now.ToString("MM-dd-yy");
string _reportName = " CSMP Pricing Workbook " + CustomerLookup.CustomerName + " " + _Created + ".xlsm";
string fileName = "C:\\BPR Projects\\CSMP Registration\\CSMP_Registration_1_03\\CSMP_Bid_Registration\\UploadedFiles\\CSMP.xlsx";
Microsoft.Office.Interop.Excel.Workbook wb = excel.Workbooks._Open(#fileName, False, False, Missing.Value, Missing.Value, False, False, Missing.Value, Missing.Value, False, Missing.Value, Missing.Value, True);
Aspose.Cells.Workbook _book = new Aspose.Cells.Workbook(fileName);
//Aspose.Cells.Worksheet _sheet = _book.Worksheets[2];
_Worksheet ws = (_Worksheet)wb.Worksheets[2];
string from = "A1";
string to = "A999";
Range rng = ws.get_Range(from, to);
Range currentFind = rng.Find("8460B001AA", Missing.Value, XlFindLookIn.xlValues, Missing.Value, Missing.Value, XlSearchDirection.xlNext, False, False, Missing.Value);
currentFind.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
currentFind.Font.Bold = true;
currentFind = currentFind.FindNext(currentFind);
while (currentFind != null)
{
Keep track of the first range you find.
if (currentFind == null)
{
currentFind = currentFind;
}
// If you didn't move to a new range, you are done.
else if (currentFind.get_Address(Microsoft.Office.Interop.Excel.XlReferenceStyle.xlA1)
== currentFind.get_Address(Microsoft.Office.Interop.Excel.XlReferenceStyle.xlA1))
{
break;
}
currentFind.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
currentFind.Font.Bold = true;
currentFind = currentFind.FindNext(currentFind);
}
_book.Save(HttpContext.Current.Response, _reportName, Aspose.Cells.ContentDisposition.Attachment, new Aspose.Cells.XlsSaveOptions(Aspose.Cells.SaveFormat.Xlsm));
}
When I export a data table to excel how can I identify how many rows are inserted to Excel, and get the next row position of the same Excel sheet to insert the next data table values?
var lines = new List<string>();
string[] columnNames = dataTable.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
var header = string.Join(",", columnNames);
lines.Add(header);
var valueLines = dataTable.AsEnumerable()
.Select(row => string.Join(",", row.ItemArray));
lines.AddRange(valueLines);
File.WriteAllLines("excel.csv",lines);
private static Microsoft.Office.Interop.Excel.Workbook mWorkBook;
private static Microsoft.Office.Interop.Excel.Sheets mWorkSheets;
private static Microsoft.Office.Interop.Excel.Worksheet mWSheet1;
private static Microsoft.Office.Interop.Excel.Application oXL;
public static void ReadExistingExcel()
{
string path = #"C:\Tool\Reports1.xls";
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item("Sheet1");
Microsoft.Office.Interop.Excel.Range range= mWSheet1.UsedRange;
int colCount = range.Columns.Count;
int rowCount= range.Rows.Count;
for (int index = 1; index < 15; index++)
{
mWSheet1.Cells[rowCount + index, 1] = rowCount +index;
mWSheet1.Cells[rowCount + index, 2] = "New Item"+index;
}
mWorkBook.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
mWSheet1 = null;
mWorkBook = null;
oXL.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
I copy the data from one location to another and am able to read and print all values. But not able to append the column in the Excel file. I need to Append three columns in the beginning (Ex: 'A').
private void btnUpload_Click(object sender, RoutedEventArgs e)
{
ApplicationClass app = new ApplicationClass();
Workbook book = null;
Worksheet sheet = null;
Range range = null;
try
{
app.Visible = false;
app.ScreenUpdating = false;
app.DisplayAlerts = false;
book = app.Workbooks.Open(#"C:\Windows\Temp\" + FileName, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value);
sheet = (Worksheet)book.Worksheets[1];
// get a range to work with
range = sheet.get_Range("A1", Missing.Value);
// get the end of values to the right (will stop at the first empty cell)
range = range.get_End(XlDirection.xlToRight);
// get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
range = range.get_End(XlDirection.xlDown);
// get the address of the bottom, right cell
string downAddress = range.get_Address(
false, false, XlReferenceStyle.xlA1,
Type.Missing, Type.Missing);
// Get the range, then values from a1
range = sheet.get_Range("A1", downAddress);
object[,] values = (object[,])range.Value2;
// Value2 is a two dimenial array dime one = row, dime two = column.
Console.WriteLine("Col Count: " + values.GetLength(1).ToString());
Console.WriteLine("Row Count: " + values.GetLength(0).ToString());
Microsoft.Office.Interop.Excel.Range oRng = sheet.Range["A1"];
oRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight,
Microsoft.Office.Interop.Excel.XlInsertFormatOrigin.xlFormatFromRightOrBelow);
oRng = sheet.Range["A1"];
oRng.Value2 = "Discount";
Microsoft.Office.Interop.Excel.Range oRng = sheet.Range["B1"];
oRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight,
Microsoft.Office.Interop.Excel.XlInsertFormatOrigin.xlFormatFromRightOrBelow);
oRng = sheet.Range["B1"];
oRng.Value2 = "NOTHING";
Microsoft.Office.Interop.Excel.Range oRng = sheet.Range["C1"];
oRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight,
Microsoft.Office.Interop.Excel.XlInsertFormatOrigin.xlFormatFromRightOrBelow);
oRng = sheet.Range["C1"];
oRng.Value2 = "HELLO";
}
catch (Exception k)
{
Console.WriteLine(k);
}
finally
{
range = null;
sheet = null;
if (book != null)
book.Close(false, Missing.Value, Missing.Value);
book = null;
if (app != null)
app.Quit();
app = null;
MessageBox.Show("File Uploaded Successfully. Please Wait...!");
}
}
You only need to set the value of the cell. Don't use "A1" as cell because you need the column number: A is the first letter, so it needs to be column 1 and B is the second letter, needs to be column 2 etc. In the following code you can see how to do it correctly:
Excel.Application app = new Excel.Application();
Excel.Workbooks workbooks = app.Workbooks;
string filename = #"yourFilename";
workbooks.Open(filename);
Excel.Workbook workbook = workbooks.Item[1];
Excel.Sheets worksheets = workbook.Worksheets;
Excel.Worksheet worksheet = worksheets.Item[1];
Excel.Range cells = worksheet.UsedRange;
cells[1, 2] = "Hello";//Set value for row 1 and column 2 (A1)
cells[1, 3] = "World";//Set value for row 1 and column 3 (B1)
workbook.Save();//Save Excel-File
app.Quit();
Console.ReadKey();
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to save an excel file that was created and written to via a C# application using the Excel Interop. I have looked all over this site as others to find a code that properly works and I have yet to find one. My excel interop funciton uses a workbook, worksheet, app, and workshee_range object. Does anyone have any suggestions. The easier the solution the better. I'm a beginner to intermediate level C# programmer and an advanced solution will likely be out of my scope of knowledge. The unhandled exception I am getting when trying to disconnect from the excel interop after saving and then closting the excel file says 'Object reference not set to an instance of an object.'
here is the code I am using to do the aforementioned process:
workbook.SaveAs(startForm.excelFileLocation);
workbook.Close();
app.Quit();
Marshal.ReleaseComObject(workSheet_range);
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(app);
app = null;
workbook = null;
worksheet = null;
workSheet_range = null;
Here is the full bit of code:
class CreateExcelDoc
{
string newFormString = trialReportForm.newFormString;
string fileString=trialReportForm.fileString;
int sheetCount;
string trialString = trialReportForm.trialString;
string dateString = trialReportForm.dateString;
string saveString = trialReportForm.saveSting;
System.Windows.Forms.Timer excelTimer = new System.Windows.Forms.Timer();
private Excel.Application app = null;
private Excel.Workbook workbook = null;
private Excel.Worksheet worksheet = null;
private Excel.Range workSheet_range = null;
public CreateExcelDoc()
{
createDoc();
}
public void createDoc()
{
try
{
app = new Excel.Application();
//app.Visible = false;
if (startForm.exportOwnerString == "Yes")
{
app.Visible = true;
startForm.exportOwnerString = " ";
}
else
{
app.Visible = false;
}
if (startForm.excelActionFlag=="addNewTrialReport")
{
workbook = (Excel.Workbook) app.Workbooks.Add(1);
//workbook.SaveAs(newFileForm.desktopPath + "\\" + "OB "+trialReportForm.otrClubNameString+" - "+trialReportForm.otrDateString);
worksheet = (Excel.Worksheet)workbook.Worksheets[1];
//fileNameString = newFileForm.desktopPath + "\\OB " + trialReportForm.otrClubNameString + " " + trialReportForm.otrDateString;
workbook.Worksheets[1].Name = trialReportForm.trialReportDate+" Trial "+trialReportForm.trialReportTrialNumber;
}
else if (startForm.excelActionFlag == "ownerContacts")
{
workbook = (Excel.Workbook)app.Workbooks.Add(1);
worksheet = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets[1].Name = "Owner Contacts";
}
else if (startForm.excelActionFlag == "newExcelResults")
{
string testFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\test";
workbook = (Excel.Workbook)app.Workbooks.Add(1);
worksheet = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets[1].Name = "Event 1 Results";
//workbook.SaveAs(testFile, Missing.Value, Missing.Value, Missing.Value, false);
//workbook.SaveAs(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"\\Results", Missing.Value, Missing.Value, Missing.Value, false);
//workbook.SaveAs(startForm.excelFileLocation, Missing.Value, Missing.Value, Missing.Value, false);
//fileNameString = registrationForm.regFileLocation + "\\OB " + registrationForm.regClubName + " " + registrationForm.regDateString;
}
else if (dogForm.dogRegistrationExcel == "Yes")
{
workbook = (Excel.Workbook)app.Workbooks.Add(1);
workbook.SaveAs(dogForm.filePath, Missing.Value, Missing.Value, Missing.Value, false);
}
else if (newFormString == "No")
{
//workbook = app.Workbooks.Open(fileString, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
// workbook.Close(true,fileString,Missing.Value);
workbook = (Excel.Workbook)app.Workbooks.Open(fileString, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
}
if (newFormString=="Yes"®istrationForm.formString=="OTR")
{
//string sheetName = "Trial Report - " + dateString + " " + trialString;
worksheet = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets[1].Name =trialReportForm.otrDateString+" Trial " + trialReportForm.otrTrialString;
//workbook.Worksheets[1].Name = "Trial Report - " + dateString + " " + trialString;
//workbook.Worksheets[1].Name = "Hello";
//Excel.Name name1 = worksheet.Names.Add("Trial Report - " + dateString + " " + trialString, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//worksheet.Name = "Trial Report - " + dateString + " " + trialString;
}
else if (newFormString == "Yes" & registrationForm.formString == "Registration")
{
//string sheetName = "Trial Report - " + dateString + " " + trialString;
worksheet = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets[1].Name = "Results: "+registrationForm.selectedEvent;
//workbook.Worksheets[1].Name = "Trial Report - " + dateString + " " + trialString;
//workbook.Worksheets[1].Name = "Hello";
//Excel.Name name1 = worksheet.Names.Add("Trial Report - " + dateString + " " + trialString, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//worksheet.Name = "Trial Report - " + dateString + " " + trialString;
}
else if (startForm.excelActionFlag == "addExistingTrialReport")
{
workbook = (Excel.Workbook)app.Workbooks.Open(startForm.excelFileLocation, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
sheetCount = workbook.Worksheets.Count;
int sheetCountPlusONe=sheetCount+1;
worksheet = (Excel.Worksheet)workbook.Worksheets.Add(Missing.Value,workbook.Worksheets[sheetCount],Missing.Value,Missing.Value);
workbook.Worksheets[sheetCountPlusONe].Name = trialReportForm.trialReportDate + " Trial " + trialReportForm.trialReportTrialNumber;
//worksheet.Move(Missing.Value, workbook.Worksheets[sheetCount]);
}
else if (startForm.excelActionFlag == "existingExcelResults")
{
workbook = (Excel.Workbook)app.Workbooks.Open(startForm.excelFileLocation, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
sheetCount = workbook.Worksheets.Count;
int sheetCountPlusONe = sheetCount + 1;
worksheet = (Excel.Worksheet)workbook.Worksheets.Add(Missing.Value, workbook.Worksheets[sheetCount], Missing.Value, Missing.Value);
workbook.Worksheets[sheetCountPlusONe].Name = "Event " + sheetCountPlusONe.ToString() + " Results";
//worksheet.Move(Missing.Value, workbook.Worksheets[sheetCount]);
}
else if (dogForm.dogRegistrationExcel == "Yes")
{
worksheet = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets[1].Name = dogForm.dogUKCNumber;
}
}
catch (Exception e)
{
Console.Write("Error");
}
/* if (trialReportForm.saveMe=="Yes")
{
workbook.Save();
workbook.Close();
}
*/
}
public void createHeaders(int row, int col, string htext, string cell1,
string cell2, int mergeColumns, string b, bool font, int size, string
fcolor)
{
worksheet.Cells[row, col] = htext;
workSheet_range = worksheet.get_Range(cell1, cell2);
workSheet_range.Merge(mergeColumns);
switch (b)
{
case "BLUE":
workSheet_range.Interior.Color = System.Drawing.Color.Red.ToArgb();
break;
case "GAINSBORO":
workSheet_range.Interior.Color =
System.Drawing.Color.Gainsboro.ToArgb();
break;
//case "Turquoise":
// workSheet_range.Interior.Color =
//System.Drawing.Color.Turquoise.ToArgb();
//break;
case "PeachPuff":
workSheet_range.Interior.Color =
System.Drawing.Color.PeachPuff.ToArgb();
break;
default:
// workSheet_range.Interior.Color = System.Drawing.Color..ToArgb();
break;
}
//workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();
//workSheet_range.Borders = null;
workSheet_range.Font.Bold = font;
workSheet_range.ColumnWidth = size;
//workSheet_range.HorizontalAlignment = ContentAlignment.BottomCenter;
if (startForm.excelActionFlag == "existingExcelResults" | startForm.excelActionFlag=="newExcelResults")
{
workSheet_range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
}
//workSheet_range.Cells.HorizontalAlignment = ContentAlignment.MiddleCenter;
workSheet_range.Font.Color = System.Drawing.Color.FloralWhite.ToArgb();
}
public void addData(int row, int col, string data,
string cell1, string cell2, string format)
{
worksheet.Cells[row, col] = data;
workSheet_range = worksheet.get_Range(cell1, cell2);
//workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();
workSheet_range.NumberFormat = format;
workSheet_range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
excelTimer.Tick += new EventHandler(excelTimer_Tick);
excelTimer.Interval = 6000;
excelTimer.Start();
}
void excelTimer_Tick(object sender, EventArgs e)
{
if (startForm.excelActionFlag != "ownerContacts")
{
if (startForm.excelActionFlag == "existingExcelResults" | startForm.excelActionFlag == "newExcelResults")
{
/* Excel.Range sortRange;
sortRange = worksheet.get_Range("A14", "K32");
Excel.Range scoreColumn;
scoreColumn = worksheet.get_Range("C14", "C32");
sortRange.Sort(scoreColumn, Excel.XlSortOrder.xlDescending);*/
Excel.Range valueRange;
Excel.Range placeRange;
placeRange = worksheet.get_Range("A14", "A" + (14 + (registrationForm.numberofCompetitors - 1)).ToString());
valueRange = worksheet.get_Range("A14", "K"+(14+(registrationForm.numberofCompetitors-1)).ToString());
valueRange.Sort(valueRange.Columns[3, Type.Missing], Excel.XlSortOrder.xlDescending, Type.Missing, Type.Missing, Excel.XlSortOrder.xlAscending, Type.Missing, Excel.XlSortOrder.xlAscending, Excel.XlYesNoGuess.xlGuess, Type.Missing, Type.Missing, Excel.XlSortOrientation.xlSortColumns, Excel.XlSortMethod.xlPinYin, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal);
placeRange.Sort(placeRange.Columns[1, Type.Missing], Excel.XlSortOrder.xlAscending, Type.Missing, Type.Missing, Excel.XlSortOrder.xlAscending, Type.Missing, Excel.XlSortOrder.xlAscending, Excel.XlYesNoGuess.xlGuess, Type.Missing, Type.Missing, Excel.XlSortOrientation.xlSortColumns, Excel.XlSortMethod.xlPinYin, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal);
}
// workbook.Close(true, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Results.xls", Missing.Value);
/*
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(workSheet_range);
Marshal.FinalReleaseComObject(worksheet);
workbook.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(workbook);
app.Quit();
Marshal.FinalReleaseComObject(app);
*/
//workbook.Close(true, startForm.excelFileLocation, Missing.Value);
workbook.SaveAs(startForm.excelFileLocation);
workbook.Close();
//app.Application.Quit();
app.Quit();
Marshal.ReleaseComObject(workSheet_range);
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(app);
app = null;
workbook = null;
worksheet = null;
workSheet_range = null;
//Application.Exit();
/* workSheet_range = null;
worksheet = null;
workbook = null;
app = null;*/
//Thread.Sleep(5000);
// File.Move(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Results.xls", startForm.excelFileLocation);
}
This means that when excelTimer_Tick is executed, the value of workbook is null (startForm can't be null, because otherwise you would have the error on if (startForm.excelActionFlag != "ownerContacts")).
I'd put a breakpoint on that line and check in the Watch window (or QuickWatch) whether it's null or not.
To see why it's null, you can refactor your workbook field into a property and put the breakpoint in the setter to see when it's set to null (or whether excelTimer_Tick is called before the field is set).