C# 如何将 Excel 工作表导出到新工作簿中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/840310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:40:49  来源:igfitidea点击:

How to export Excel worksheets into new workbooks

c#.netvb.netexcel

提问by Chris Burgess

I have a bunch of Excel workbooks that contain multiple worksheets. I want to loop through each workbook and export each worksheet into it's own new workbook. I want one worksheet in each new workbook.

我有一堆包含多个工作表的 Excel 工作簿。我想遍历每个工作簿并将每个工作表导出到它自己的新工作簿中。我希望每个新工作簿中有一个工作表。

Here's what I've got so far:

这是我到目前为止所得到的:

   Sub ExportWorksheet(ByVal worksheet As Excel.Worksheet, ByVal filePath As String)
      Dim xlApp As Excel.Application = New Excel.ApplicationClass
      Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Add
      worksheet.Select()
      worksheet.Copy()
      xlWorkBook.Worksheets.Add()
      worksheet.Paste(Destination:=xlWorkBook)

      xlWorkBook.SaveAs(Filename:=filePath)

      xlWorkBook.Close(False)
      xlApp.Quit()
   End Sub

采纳答案by Chris Burgess

Doh!

哦!

worksheet.SaveAs(Filename:=filePath)

worksheet.SaveAs(Filename:=filePath)

回答by Lunatik

Within Excel this would be accomplished by copying the worksheet to a new workbook, not by creating a new workbook then adding the worksheet to it. This is achieved by using Worksheet.Copywithout specifying where in the workbook you want to place the copied worksheet.

在 Excel 中,这可以通过将工作表复制到新工作簿来完成,而不是通过创建新工作簿然后将工作表添加到其中来完成。这是通过使用Worksheet.Copy而不指定要在工作簿中放置复制的工作表的位置来实现的。

More reading: http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.worksheet.copy(VS.80).aspx

更多阅读:http: //msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.worksheet.copy(VS.80).aspx