C# Excel - save each worksheet to a new workbook

前端 未结 3 1735
南方客
南方客 2020-12-18 06:30

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 individ

3条回答
  •  醉话见心
    2020-12-18 07:11

    Try this in place of your current for loop and below

        foreach(Worksheet sheet in workBook.Worksheets)
        {
            var newbook = app.Workbooks.Add(1);
            sheet.Copy(newbook.Sheets[1]);
    
            newbook.SaveAs(FileDropLocation + "\\" + sheet.Name);
            newbook.Close();
        }
    
        workBook.Close();
    

    Just 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.

提交回复
热议问题