C# Excel - 将每个工作表保存到新工作簿

excel

1个回答

写回答

Monica333

2025-07-02 23:50

+ 关注

excel
excel

将每个工作表保存到新工作簿是在C#中使用excel进行操作的一个常见需求。使用C#语言编写代码可以轻松地实现这一功能。本文将介绍如何使用C#代码将每个工作表保存到新工作簿,并提供一个案例代码供参考。

在C#中,可以使用Microsoft.Office.Interop.excel命名空间提供的类和方法来操作excel。首先,需要在项目中引用Microsoft.Office.Interop.excel.dll文件。

下面是一个示例代码,演示了如何将每个工作表保存到新工作簿:

csharp

using System;

using System.IO;

using excel = Microsoft.Office.Interop.excel;

namespace excelExample

{

class Program

{

static void MAIn(string[] args)

{

// 打开excel应用程序

excel.Application excelApp = new excel.Application();

excelApp.Visible = false; // 不显示excel窗口

// 打开工作簿

excel.Workbook workbook = excelApp.Workbooks.Open(@"C:\path\to\your\workbook.xlsx");

try

{

// 遍历每个工作表

foreach (excel.Worksheet worksheet in workbook.Worksheets)

{

// 创建新的工作簿

excel.Workbook newWorkbook = excelApp.Workbooks.Add();

excel.Worksheet newWorksheet = newWorkbook.Worksheets[1];

// 将当前工作表的数据复制到新的工作簿

worksheet.Copy(newWorksheet);

// 保存新的工作簿

string newWorkbookPath = Path.Combine(@"C:\path\to\save", worksheet.Name + ".xlsx");

newWorkbook.SaveAs(newWorkbookPath);

// 关闭新的工作簿

newWorkbook.Close();

}

}

finally

{

// 关闭工作簿和excel应用程序

workbook.Close();

excelApp.Quit();

}

}

}

}

上面的代码首先打开excel应用程序,并将其设置为不可见。然后打开要处理的工作簿。接下来,使用foreach循环遍历每个工作表。在循环中,创建一个新的工作簿,并将当前工作表的数据复制到新的工作簿中。然后将新的工作簿保存到指定的路径,并关闭新的工作簿。最后,关闭工作簿和excel应用程序。

通过以上代码,可以将每个工作表保存到新的工作簿中。这对于需要将工作簿中的每个工作表分别处理的情况非常有用。你可以根据自己的需求进行修改和扩展。

案例代码:

csharp

using System;

using System.IO;

using excel = Microsoft.Office.Interop.excel;

namespace excelExample

{

class Program

{

static void MAIn(string[] args)

{

// 打开excel应用程序

excel.Application excelApp = new excel.Application();

excelApp.Visible = false; // 不显示excel窗口

// 打开工作簿

excel.Workbook workbook = excelApp.Workbooks.Open(@"C:\path\to\your\workbook.xlsx");

try

{

// 遍历每个工作表

foreach (excel.Worksheet worksheet in workbook.Worksheets)

{

// 创建新的工作簿

excel.Workbook newWorkbook = excelApp.Workbooks.Add();

excel.Worksheet newWorksheet = newWorkbook.Worksheets[1];

// 将当前工作表的数据复制到新的工作簿

worksheet.Copy(newWorksheet);

// 保存新的工作簿

string newWorkbookPath = Path.Combine(@"C:\path\to\save", worksheet.Name + ".xlsx");

newWorkbook.SaveAs(newWorkbookPath);

// 关闭新的工作簿

newWorkbook.Close();

}

}

finally

{

// 关闭工作簿和excel应用程序

workbook.Close();

excelApp.Quit();

}

}

}

}

在本文中,我们介绍了如何使用C#代码将每个工作表保存到新工作簿。通过使用Microsoft.Office.Interop.excel命名空间提供的类和方法,我们可以轻松地实现这一功能。以上给出的案例代码可以作为参考,并根据实际需求进行修改和扩展。希望本文能帮助你在C#中进行excel操作。

举报有用(4)分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号