合并文件

介绍

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");