Disconnect from Microsoft Excel Interop without crashing host C# program - c#
I have a C# program that is creating, writing, and saving an excel file using the Excel Interop. The problem is that if I don't have the application quit immediately after saving and closing the excel file then the c# application gets an unhandled exception and crashes. Has anyone found a way to do this while being able to keep the host c# application open and running.
Here is the code that handles everything involving the Excel Interop
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);
workbook.Close(true, startForm.excelFileLocation, Missing.Value);
app.Quit();
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);
}
}
}
I find that when saving with excel, I have more luck using the SaveAs method. For example:
private static Microsoft.Office.Interop.Excel.Application xlApp = null;
private static Microsoft.Office.Interop.Excel.Workbook xlWb = null;
private static Microsoft.Office.Interop.Excel.Worksheet xlWs = null;
//Your code and operations
xlWb.SaveAs(filePath, XlFileFormat.xlExcel8, Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlNoChange,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
xlApp.Quit();
Marshal.ReleaseComObject(xlWs);
Marshal.ReleaseComObject(xlWb);
Marshal.ReleaseComObject(xlApp);
Several solutions including mine are presented How do I properly clean up Excel interop objects?
You can choose among the most sever (Killing Excel process) to more tender solutions (releasing COM object)
Related
How to find the row count of an Excel table using ASP.NET?
I am using the below mentioned code for finding the row count of an Excel table but it seems there is something wrong since I am not getting the desired output. Please provide some solution to it. The code is as follows: using Excel = Microsoft.Office.Interop.Excel; Excel.Application xlApp = null; Excel.Workbook wb = null; Excel.Worksheet worksheet = null; int lastUsedRow = 0; string srcFile = #"Path to your XLSX file"; xlApp = new Excel.ApplicationClass(); xlApp.Visible = false; wb = xlApp.Workbooks.Open(srcFile, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false); worksheet = (Excel.Worksheet)wb.Worksheets[1]; Excel.Range range // Find the last real row lastUsedRow = worksheet.Cells.Find("*",System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSearchOrder.xlByRows,Excel.XlSearchDirection.xlPrevious, false,System.Reflection.Missing.Value,System.Reflection.Missing.Value).Row; xlApp.Workbooks.Close(); xlApp.Quit(); Marshal.ReleaseComObject(worksheet); Marshal.ReleaseComObject(wb); Marshal.ReleaseComObject(xlApp);
You can try: wb = xlApp.Workbooks.Open(srcFile, 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); worksheet = (Excel.Worksheet)wb.Worksheets[1]; object[,] values = worksheet .UsedRange.Value2; int rowCount = values.GetLength(0); int colCount = values.GetLength(1);
Setting border property in excel using c# is not working in case of multiple excel file
I am designing a small program using Microsoft.Office.Interop.Excel library in c#. My program read the excel files(whose names are 1.xlss,2.xlsx and so on) and make a new excel file and then copy the data of all excel files into new excel files with one line gap. I also set the certain property like border,font,backgroundcolor etc of the cells. Everything is fine for first excel file(1.xls) but in case of 2nd,3rd and so on, It's not setting the border property of the cells.Here is my code // data member initialization for reading the sheet Excel.Application app; Excel.Workbook workbook; Excel.Worksheet worksheet; Excel.Range range; // data member initialization for writing sheet Excel.Application finalApp; Excel.Workbook finalWorkBook; Excel.Worksheet finalWorkSheet; String path = this.textBox1.Text; String numberOfFiles = (String)this.comboBox1.SelectedItem; int count = 1; int row = 1, col = 1; try { // Object creation for the final sheet finalApp = new Excel.ApplicationClass(); finalApp.Visible = true; finalWorkBook = finalApp.Workbooks.Add(1); finalWorkSheet = (Excel.Worksheet)finalWorkBook.Sheets[1]; // opening a excel file app = new Excel.ApplicationClass(); Excel.Borders b=null; Excel.Borders fb = null; try { for (int k = 0; k < Int32.Parse(numberOfFiles); k++) { fullPath = #path + #"\" + count + ".xlsx"; workbook = app.Workbooks.Open(fullPath, 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); worksheet = (Excel.Worksheet)workbook.Sheets.get_Item(1); range = worksheet.UsedRange; int cnum1 = range.Columns.Count; int rnum1 = range.Rows.Count; int i, j; for (i = 1; i <= rnum1; i++) { for (j = 1; j <= cnum1; j++) { if ((range.Cells[i, j] as Excel.Range).Value2 != null) { string value1 = (range.Cells[i, j] as Excel.Range).Value2.ToString(); finalWorkSheet.Cells[row, col] = value1; b= (Excel.Borders)(range.Cells[i, j] as Excel.Range).Borders; //MessageBox.Show(b.Weight.ToString()); fb=(finalWorkSheet.Cells[i, j] as Excel.Range).Borders; fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Weight= b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Weight; fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].Weight = b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].Weight; fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].Weight = b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].Weight; fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Weight = b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Weight; fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].LineStyle = b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].LineStyle; fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].LineStyle = b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].LineStyle; fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].LineStyle = b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].LineStyle; fb[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].LineStyle = b[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].LineStyle; //fb.Color = b.Color; //(finalWorkSheet.Cells[i, j] as Excel.Range).BorderAround(b.LineStyle,(Excel.XlBorderWeight)b.Weight, //(Excel.XlColorIndex)b.ColorIndex,b.Color); } (finalWorkSheet.Cells[row, col] as Excel.Range).Interior.Color = (range.Cells[i, j] as Excel.Range).Interior.Color; (finalWorkSheet.Cells[row, col] as Excel.Range).Font.Color = (range.Cells[i, j] as Excel.Range).Font.Color; col++; } row++; col = 1; } //finalWorkBook.SaveAs("hello.xlsx", Excel.XlFileFormat.xlExcel4Workbook, Missing.Value, //Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, //Missing.Value, Missing.Value, Missing.Value); workbook.Close(false, false, Missing.Value); count++; row++; col = 1; } } catch (FileNotFoundException fnfe) { MessageBox.Show("Error while opening the file "+fullPath); } //finalWorkBook.Close(true,false,Missing.Value); } catch (Exception ex) { MessageBox.Show(#"Some Error has occurred.Please check the path Correctly whether it's correct or not"); } } Any help would be appreciated.
fb=(finalWorkSheet.Cells[i, j] as Excel.Range).Borders; Should be fb=(finalWorkSheet.Cells[row, col] as Excel.Range).Borders;
Save an excel file in c#
void excelsave() { try { ApplicationClass app = new ApplicationClass(); // the Excel application. Workbook book = null; Worksheet sheet = null; Range range = null; // the range object is used to hold the data app.Visible = false; app.ScreenUpdating = false; app.DisplayAlerts = false; string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase); book = app.Workbooks.Open(#"E:\SSIS\ABC\Book1.xls", 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]; range = sheet.get_Range("A1", Missing.Value); range.Columns.ColumnWidth = 22.34; range = sheet.get_Range("B1", Missing.Value); range.Columns.ColumnWidth = 22.34; book.SaveAs(#"E:\SSIS\ABC\Book1.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } catch (Exception ex) { } } Here I am opening an excel sheet trying to increase the column width and need to make the column headers as bold and save the document, right now the document is not getting saved. I am using vs 2008, c# 3.5 Is There anything that I am doing wrong here? any help on this would be great looking an for solution
I ran the following using VS 2010 and .NET 4, but this code should still work in your environment. Also, I simplified your code a bit. Hopefully this will get you going in the right direction. static void excelsave() { try { Application app = new Application(); string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase); Workbook book = app.Workbooks.Open(#"c:\test.xls"); Worksheet sheet = (Worksheet)book.Worksheets[1]; Range range = sheet.get_Range("A1"); range.Columns.ColumnWidth = 22.34; range = sheet.get_Range("B1"); range.Columns.ColumnWidth = 22.34; sheet.get_Range("A1", "B1").Font.Bold = true; book.SaveAs(#"c:\test2.xls"); // or book.Save(); book.Close(); } catch (Exception ex) { } } UPDATE You can find a similar explanation/example of what you are doing at: http://www.dotnetperls.com/excel Marshal.ReleaseComObject(book); // do this after the close Also, there is a good discussion on cleaning up Excel/COM ... How To Properly Clean Up Excel Interop Objects In c#
com exception HRESULT: 0x800A03EC
I write a c# program for copy sheet. I got the exception error(0x800A03EC) when I call WorkSheet.Copy method until 105 times. This is my snippet code: using Microsoft.Office.Interop.Excel; private void CreateSheet(string dst_fileName) { object cell1 = "A2"; ApplicationClass app = null; Workbook book = null; Worksheet sheet = null; Worksheet sheet_to_copy = null; int i=0; try { app = new ApplicationClass(); app.Visible = false; app.ScreenUpdating = false; app.DisplayAlerts = false; book = app.Workbooks.Open(dst_fileName, 0, false, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); // Reference to the worksheet sheet_to_copy = (Worksheet)book.Worksheets[1]; for(;i<listViewPrg.Items.Count;i++) { sheet = (Worksheet)book.Worksheets[book.Worksheets.Count]; // Copy the worksheet to the end of the worksheets sheet_to_copy.Copy(Missing.Value, sheet); sheet.Name = "NewSheet(" + book.Worksheets.Count + ")"; } book.SaveAs(dst_fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { QuitExcel(app); } } I can't found any solution about this. Could someone give me a hint to solve this problem? Thank you so much.
Possibly you have some corrupted Excel registry entries or so? Why don't you try to use an open source reader of excel files and do everything using them? The speed would skyrocket and i guarantee you would not get these errors!
Error - Index refers beyond end of list
Problem saving file back to SharePoint with Excel COM lib. I open the file but it opens as 'xlviewer.xlsx' so I assume I need to overwrite the original file. (I removed the try/catch to do some error handling.) When I do I get this error: "Index refers beyond end of list" (error at line: 42 'SaveAs statement') using System; using System.Collections.Generic; using System.Linq; using System.Text; using Excel = Microsoft.Office.Interop.Excel; using System.Reflection; using System.IO; namespace CopyInteractionIds { class Program { static void Main(string[] args) { Excel.Application oApp; Excel._Workbook oWbFrom; Excel._Workbook oWbTo; Excel._Worksheet oWsFrom; Excel._Worksheet oWsTo; Excel.Range oRngFrom; Excel.Range oRngTo; //try //{ oApp = new Excel.Application(); oApp.Visible = true; Console.WriteLine("Opening source workbook"); oWbFrom = (Excel._Workbook)(oApp.Workbooks.Open(#"path to my source wb" , 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)); Console.WriteLine("Opening edited workbook"); oWbTo = (Excel._Workbook)(oApp.Workbooks.Open(#"https://path to my out wb" , Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value , Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value)); Console.WriteLine("Copying data"); oWsFrom = (Excel._Worksheet)oWbFrom.Worksheets.get_Item("Interaction Number Lookup"); oWsTo = (Excel._Worksheet)oWbTo.Worksheets.get_Item("Interaction Number Lookup"); oRngFrom = oWsFrom.get_Range("=OFFSET($A$1,0,0,COUNTA($A:$A),COUNTA($1:$1))",Missing.Value); oWsTo.get_Range("=OFFSET($A$1,0,0,COUNTA($A:$A),COUNTA($1:$1))", Missing.Value).Clear(); oRngTo = oWsTo.get_Range("A1",Missing.Value); oRngFrom.Copy(oRngTo); Console.WriteLine("Saving edited file"); oWbTo.SaveAs(#"path to out file" , Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value ,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Missing.Value , Missing.Value, Missing.Value, Missing.Value, Missing.Value); oWbTo.Close(false,Missing.Value,Missing.Value); oWbFrom.Close(false, Missing.Value, Missing.Value); oApp.Quit(); //} //catch(Exception ex) //{ // Console.WriteLine("Unable to process job: {0}",ex.Message); //} } } }
I had a similar issue, it turned out my files were "damaged". Opening them all, having Excel repair them and then overwriting the damaged files seemed to do the trick for me.
Someone else had the file open.