合并文件

介绍

Aspose.Cells提供了不同的方式来合并文件。对于简单的包含数据、格式和公式的文件,可以使用Workbook.Combine()方法来合并多个工作簿,使用Worksheet.Copy()方法将工作表复制到新工作簿。这些方法使用简单且有效,但如果要合并大量文件,可能需要大量系统资源。为了避免这种情况,使用更高效的方法CellsHelper.MergeFiles静态方法来合并多个文件。

使用Aspose.Cells合并文件

以下示例代码演示了如何使用CellsHelper.MergeFiles方法合并大型文件。它使用两个简单但大型的文件,Book1.xls和Book2.xls。这些文件仅包含格式化的数据和公式。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create an Array (length=2)
string[] files = new string[2];
// Specify files with their paths to be merged
files[0] = dataDir + "Book1.xls";
files[1] = dataDir + "Book2.xls";
// Create a cachedFile for the process
string cacheFile = dataDir + "test.txt";
// Output File to be created
string dest = dataDir + "output.xlsx";
// Merge the files in the output file. Supports only .xls files
CellsHelper.MergeFiles(files, cacheFile, dest);
// Now if you need to rename your sheets, you may load the output file
Workbook workbook = new Workbook(dataDir + "output.xlsx");
int i = 1;
// Browse all the sheets to rename them accordingly
foreach (Worksheet sheet in workbook.Worksheets)
{
sheet.Name = "Sheet1" + i.ToString();
i++;
}
// Re-save the file
workbook.Save(dataDir + "output.xlsx");