aspose.cells java合并多个excel
背景
有需求需要把多个excel合并到一个excel文件里面,之前一直都是用python来处理办公自动化的东西,但是这个需求用python的openxyl库处理基本只能合并数据,样式没办法一比一合并过去,找了很多解决方案都没法实现,所以只能另寻途径,在网上找到一个在线合并excel的网站,看了一下他们实现的技术是用aspose.cells的,合并效果不错,但是在线合并一次只能合并10个,并且速度有点慢,所以决定自己用aspose.cells写一个工具类来用,下面贴出合并excel的代码。
依赖
<dependency>
<groupId>com.luhuiguo</groupId>
<artifactId>aspose-cells</artifactId>
<version>23.1</version>
</dependency>
import com.aspose.cells.Workbook;
import com.aspose.cells.Worksheet;
import com.aspose.cells.WorksheetCollection;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class demo {
public static void main(String[] args) throws Exception {
String folderPath = "";
Workbook workbook2 = new Workbook();
WorksheetCollection worksheets = workbook2.getWorksheets();
workbook2.getWorksheets().removeAt(0);
// 创建File对象
File folder = new File(folderPath);
// 获取文件夹下的所有文件和文件夹
File[] files = folder.listFiles();
Arrays.sort(files, (f1, f2) -> Integer.valueOf(f1.getName().split("、")[0].split("-")[1]).compareTo(Integer.valueOf(f2.getName().split("、")[0].split("-")[1])));
// 遍历并打印文件名
for (File file : files) {
System.out.println(file.getName());
String[] split = file.getName().split("、");
String regex = "【(.*?)】";
// 创建Pattern对象
Pattern pattern = Pattern.compile(regex);
// 要匹配的字符串
String input = file.getName();
// 创建Matcher对象
Matcher matcher = pattern.matcher(input);
ArrayList arrayList = new ArrayList();
while (matcher.find()) {
// System.out.println("找到匹配项: " + matcher.group());
arrayList.add( matcher.group());
}
System.out.println(arrayList.get(arrayList.size()-1));
String name = arrayList.get(arrayList.size()-1).toString().replace("【","").replace("】","");
Workbook workbook = new Workbook(folderPath+file.getName());
if (name.length() >= 25){
name=name.split("-")[0];
}
worksheets.add(split[0]+"、"+name);
worksheets.get(split[0]+"、"+name).copy(workbook.getWorksheets().get("1-指标清单"));
}
// 保存Excel文件
workbook2.save("output.xlsx");
}
}