Therefore, I was making an Excel sheet aggregator. In my line of business, we occasionally receive a large number of separate Excel files with only one sheet each that are all related.
I partially adopted the concepts from the prior post. But after doing so, I noticed that several of the duplicated excel sheets were empty. only some of them. Why some are blank and others are fine is beyond my comprehension.
The code I employ to access and copy Excel files is shown below.
OpenFileDialog browse = new OpenFileDialog();
browse.Multiselect = true;
DialogResult result = browse.ShowDialog();
if (result == DialogResult.OK)
try //try to open it. If its a proper excel file
{
excel = new Excel.Application();
excel.Workbooks.Add("");
finalized = excel.Workbooks[1];
excel.SheetsInNewWorkbook = 1;
for(int i=0; i< browse.FileNames.Length; i++)
{
excel.Workbooks.Add(browse.FileNames[i]);
}
//skip the first workbook as it is the finalized one
//also note everything in excel starts at 1 and not 0
for(int i=2; i<excel.Workbooks.Count; i++)
{
int count = excel.Workbooks[i].Worksheets.Count;
excel.Workbooks[i].Activate();
for (int j = 1; j < count; j++)
{
Excel._Worksheet pastee = (Excel._Worksheet)excel.Workbooks[i].Worksheets[j];
Excel._Worksheet sheet = (Excel._Worksheet)finalized.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//Excel._Worksheet sheet = finalized.Sheets[1];
pastee.Copy(Before: sheet);
}//end of for j
}//end of for i
}//end of try
Here is the code I use to save the excel file
SaveFileDialog browse = new SaveFileDialog();
browse.Title = "Save as Excel";
browse.Filter = "Excel workbook | *.xlsx";
DialogResult result = browse.ShowDialog();
finalized.SaveAs(browse.FileName, Excel.XlFileFormat.xlWorkbookDefault);
MessageBox.Show("Success", "Message");
//unlock the file
Global.releaseComObjects(finalized, excel);