合并文件

介绍

Aspose.Cells提供了不同的合并文件的方法。对于含有数据、格式和公式的简单文件,可以使用Workbook.combine()方法合并多个工作簿,并可以使用Worksheet.copy()方法将工作表复制到新工作簿中。这些方法易于使用且有效,但如果有大量要合并的文件,您可能会发现它们占用大量系统资源。为避免这种情况,使用CellsHelper.mergeFiles静态方法,这是合并多个文件的更高效方法。

使用Aspose.Cells合并文件

以下示例代码说明了如何使用CellsHelper.mergeFiles方法合并大文件。它包括两个简单但很大的文件,MyBook1.xls和MyBook2.xls。这些文件只包含格式化数据和公式。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getSharedDataDir(MergeFiles.class) + "CellsHelperClass/";
// 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 + "MergeFiles_out.xls";
// Merge the files in the output file
CellsHelper.mergeFiles(files, cacheFile, dest);
// Now if you need to rename your sheets, you may load the output file
Workbook workbook = new Workbook(dataDir + "MergeFiles_out.xls");
int cnt = 1;
// Browse all the sheets to rename them accordingly
for (int i = 0; i < workbook.getWorksheets().getCount(); i++) {
workbook.getWorksheets().get(i).setName("Sheet1" + cnt);
cnt++;
}
// Re-save the file
workbook.save(dataDir + "MergeFiles1_out.xls");