I have an excel with 25 or so worksheets I just want to save each worksheet as it's own new Workbook. When I run the code it copys the entire workbook just not the individual sheet. Any help would be awesome.
string FileDropLocation = @"C:\ExcelFiles";
string file_FullFileName = @"C:\ts\Conversion\v2.xlsx";
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Open(file_FullFileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
for (int i = 0; i < workBook.Worksheets.Count; i++)
{
Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets[i+1];
workSheet.SaveAs(FileDropLocation + "\\" + workSheet.Name);
}
workBook.Close();
I know this works.
... You need to create a new workbook in your loop and move the sheet to that workbook. I program in VB, so i'm guessing, but the code inside your foor loop should look something like this:
Then you can add code to delete the other sheets, etc.
Hope tihs helps.
Try this in place of your current
for
loop and belowJust to note, I believe
Workbooks.Add()
places in a default blank sheet (typically Sheet1), so if you want just the copied sheet you'll have to explicitly remove it.