本教程将演示如何通过Spire.XLS for .NET来将一个Excel工作表按指定范围拆分为多个工作表。关于Excel工作表合并请查阅这篇教程 - C# 如何合并Excel文档。
测试文档:
C#
//加载Excel工作簿,并获取第一张工作表
Workbook bookOriginal = new Workbook();
bookOriginal.LoadFromFile("sample.xlsx");
Worksheet sheet = bookOriginal.Worksheets[0];
//新建工作簿1
Workbook newBook1 = new Workbook();
//获取源excel工作表中第1行至第10行的数据,将它们复制到newBook1的第一个工作表
Worksheet newSheet1 = newBook1.Worksheets[0];
CellRange range1 = sheet.Range[1, 1, 10, sheet.LastColumn];
sheet.Copy(range1, newSheet1.Range[1, 1]);
//重复以上操作步骤
Workbook newBook2 = new Workbook();
Worksheet newSheet2 = newBook2.Worksheets[0];
CellRange range2 = sheet.Range[11, 1, 17, sheet.LastColumn];
sheet.Copy(range2, newSheet2.Range[1, 1],true);
Workbook newBook3 = new Workbook();
Worksheet newSheet3 = newBook3.Worksheets[0];
CellRange range3 = sheet.Range[18, 1, 26, sheet.LastColumn];
sheet.Copy(range3, newSheet3.Range[1, 1],true);
//保存三个excel文件
newBook1.SaveToFile("表1.xlsx", ExcelVersion.Version2010);
newBook2.SaveToFile("表2.xlsx", ExcelVersion.Version2010);
newBook3.SaveToFile("表3.xlsx", ExcelVersion.Version2010);
VB.NET
'加载Excel工作簿,并获取第一张工作表
Dim bookOriginal As New Workbook()
bookOriginal.LoadFromFile("sample.xlsx")
Dim sheet As Worksheet = bookOriginal.Worksheets(0)
'新建工作簿1
Dim newBook1 As New Workbook()
'获取源excel工作表中第1行至第10行的数据,将它们复制到newBook1的第一个工作表
Dim newSheet1 As Worksheet = newBook1.Worksheets(0)
Dim range1 As CellRange = sheet.Range(1, 1, 10, sheet.LastColumn)
sheet.Copy(range1, newSheet1.Range(1, 1))
'重复以上操作步骤
Dim newBook2 As New Workbook()
Dim newSheet2 As Worksheet = newBook2.Worksheets(0)
Dim range2 As CellRange = sheet.Range(11, 1, 17, sheet.LastColumn)
sheet.Copy(range2, newSheet2.Range(1, 1), True)
Dim newBook3 As New Workbook()
Dim newSheet3 As Worksheet = newBook3.Worksheets(0)
Dim range3 As CellRange = sheet.Range(18, 1, 26, sheet.LastColumn)
sheet.Copy(range3, newSheet3.Range(1, 1), True)
'保存三个excel文件
newBook1.SaveToFile("表1.xlsx", ExcelVersion.Version2010)
newBook2.SaveToFile("表2.xlsx", ExcelVersion.Version2010)
newBook3.SaveToFile("表3.xlsx", ExcelVersion.Version2010)
拆分结果: