ralphtrent
Programmer
Hello
I have multiple excel files that contain a single worksheet. I would like to save them all in one workbook. The code I have put together does add a blank worksheet to the workbook, but not the worksheet from the excel doc I am telling it to grab from. Here is my code.
Any help is appreciated.
I have multiple excel files that contain a single worksheet. I would like to save them all in one workbook. The code I have put together does add a blank worksheet to the workbook, but not the worksheet from the excel doc I am telling it to grab from. Here is my code.
Code:
private void btnMergeOutputFiles_Click(object sender, EventArgs e)
{
string sMergedFileName = txtOutputFolder.Text + "\\MergedFiles.xls";
int i = 0;
while (System.IO.File.Exists(sMergedFileName))
{
i++;
sMergedFileName = txtOutputFolder.Text + "\\MergedFiles" + i.ToString().PadLeft(3, '0') + ".xls";
}
Microsoft.Office.Interop.Excel.ApplicationClass exApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook exMergedWorkBook = exApp.Workbooks.Add(System.Reflection.Missing.Value);
try
{
foreach (object objOutputFile in lbOutputFiles.Items)
{
Microsoft.Office.Interop.Excel.Workbook exWorkBook = exApp.Workbooks._Open(objOutputFile.ToString(), Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
try
{
Microsoft.Office.Interop.Excel.Worksheet exWS = (Microsoft.Office.Interop.Excel.Worksheet)exWorkBook.Sheets[1];
exMergedWorkBook.Sheets.Copy(exWS, Type.Missing);
}
catch
{
throw;
}
finally
{
exWorkBook.Close(false, null, null);
exWorkBook = null;
}
}
exMergedWorkBook.SaveAs(sMergedFileName, Type.Missing, "", "", Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
catch (Exception ex)
{
Common.DisplayException(ex, this);
}
finally
{
exMergedWorkBook.Close(null, null, null);
exMergedWorkBook = null;
exApp = null;
lbOutputFiles.Items.Add(sMergedFileName);
}
}