翻譯|使用教程|編輯:胡濤|2022-02-21 11:22:11.817|閱讀 539 次
概述:很多時候我們必須同時打開多個 Excel 文件時,合并相同類型或類別的 Excel 文件可以幫助我們避免麻煩,節省我們很多時間,本文將演示如何使用Spire.XLS for .NET庫在 VB.NET 中將 Excel 文件合并為一個。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
當我們必須同時打開多個 Excel 文件時,合并相同類型或類別的 Excel 文件可以幫助我們避免麻煩并節省我們很多時間,本文將演示如何使用 Spire.XLS for .NET 庫在 VB.NET 中將 Excel 文件合并為一個。
首先,您需要添加 Spire.XLS for .NET 包中包含的 DLL 文件作為 .NET 項目中的引用。
PM> Install-Package Spire.XLS
以下是將多個 Excel 工作簿合并為一個的步驟:
using Spire.Xls;
namespace MergeExcelFiles
{
class Program
{
static void Main(string[] args)
{
//Create a string array from Excel file paths
string[] inputFiles = new string[] { "April.xlsx", "May.xlsx", "June.xlsx" };
//Initialize a new Workbook object
Workbook newWorkbook = new Workbook();
//Clear the default worksheets
newWorkbook.Worksheets.Clear();
//Initialize another temporary Workbook object
Workbook tempWorkbook = new Workbook();
//Loop through the string array
foreach (string file in inputFiles)
{
//Load the current workbook
tempWorkbook.LoadFromFile(file);
//Loop through the worksheets in the current workbook
foreach (Worksheet sheet in tempWorkbook.Worksheets)
{
//Copy each worksheet from the current workbook to the new workbook
newWorkbook.Worksheets.AddCopy(sheet, WorksheetCopyType.CopyAll);
}
}
//Save the new workbook to file
newWorkbook.SaveToFile("MergeWorkbooks.xlsx", ExcelVersion.Version2013);
}
}
}
輸入 Excel 工作簿:
合并的 Excel 工作簿:
我們可以將相同或不同工作簿中的多個工作表合并為一個。以下步驟顯示如何將同一工作簿中的兩個 Excel 工作表合并為一個工作表:
using Spire.Xls;
namespace MergeExcelWorksheets
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook object
Workbook workbook = new Workbook();
//Load an Excel file
workbook.LoadFromFile("Sample.xlsx");
//Get the first worksheet
Worksheet sheet1 = workbook.Worksheets[0];
//Get the second worksheet
Worksheet sheet2 = workbook.Worksheets[1];
//Get the used range in the second worksheet
CellRange sourceRange = sheet2.AllocatedRange;
//Specify the destination range in the first worksheet
CellRange destRange = sheet1.Range[sheet1.LastRow + 1, 1];
//Copy the used range of the second worksheet to the destination range in the first worksheet
sourceRange.Copy(destRange);
//Remove the second worksheet
sheet2.Remove();
//Save the result file
workbook.SaveToFile("MergeWorksheets.xlsx", ExcelVersion.Version2013);
}
}
}
輸入 Excel 工作表:
合并的 Excel 工作表:
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@ke049m.cn