import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author: guanglai.zhou
* @date: 2023/4/3 13:23
*/
public class SheetCopyUtils {
/**
* 根据源Sheet拷贝一个新的Sheet,然后进行操作
* 如果拷贝完成而且操作完成 则返回true
*
* @param sourceSheetName 源sheet名称
* @param targetSheetName 目标sheet名称
* @param filePath 文件路径
*/
public static boolean copySheet(String sourceSheetName, String targetSheetName, String filePath, int newSheetIndex, SheetCallBack sheetCallBack) {
try (Workbook workbook = WorkbookFactory.create(new FileInputStream(filePath))) {
Sheet sheet = workbook.getSheet(targetSheetName);
if (sheet != null) {
return false;
}
Sheet sourceSheet = workbook.getSheet(sourceSheetName);
Sheet targetSheet = workbook.cloneSheet(workbook.getSheetIndex(sourceSheet));
workbook.setSheetName(workbook.getSheetIndex(targetSheet), targetSheetName);
// 执行各种回调操作
boolean shouldSave = sheetCallBack.doEdit(sourceSheet, targetSheet);
if (!shouldSave) {
return false;
}
// 将结果写入到excel当中
try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
workbook.write(fileOut);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
try (Workbook workbook = WorkbookFactory.create(new FileInputStream(filePath))) {
workbook.setSheetOrder(targetSheetName, newSheetIndex);
// 将结果写入到excel当中
try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
workbook.write(fileOut);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
public interface SheetCallBack {
/**
* @param sourceSheet 源Sheet页对象
* @param targetSheet 目标Sheet页对象
* @return 编辑操作是否需要保存
*/
boolean doEdit(Sheet sourceSheet, Sheet targetSheet);
}
}
通过POI拷贝sheet页并编辑
最新推荐文章于 2024-11-04 20:33:37 发布
该代码示例展示了如何使用ApachePOI库在Java中复制一个Excel工作表,并根据提供的回调函数对新工作表进行操作。方法接收源Sheet名、目标Sheet名、文件路径、新Sheet的索引和一个SheetCallBack接口,该接口用于执行自定义编辑。如果操作成功并需要保存,文件将被更新并返回true。
摘要由CSDN通过智能技术生成