java 操作excel 复制sheet生成新的excel
时间: 2023-07-07 18:17:37 浏览: 734
可以使用 Apache POI 库来操作 Excel 文件,以下是复制 sheet 并生成新的 Excel 文件的示例代码:
```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtil {
public static void copySheet(String srcFilePath, String srcSheetName, String destFilePath, String destSheetName) throws Exception {
FileInputStream fileInputStream = new FileInputStream(srcFilePath);
Workbook workbook = new XSSFWorkbook(fileInputStream);
Sheet srcSheet = workbook.getSheet(srcSheetName);
Sheet destSheet = workbook.cloneSheet(workbook.getSheetIndex(srcSheet));
workbook.setSheetName(workbook.getSheetIndex(destSheet), destSheetName);
workbook.removeSheetAt(workbook.getSheetIndex(srcSheet));
fileInputStream.close();
FileOutputStream fileOutputStream = new FileOutputStream(destFilePath);
workbook.write(fileOutputStream);
fileOutputStream.close();
}
}
```
在这个方法中,我们首先打开源 Excel 文件并获取目标 sheet。然后,我们使用 `cloneSheet()` 方法复制 sheet,并使用 `setSheetName()` 方法将其重命名为目标 sheet 名称。接下来,我们删除源 sheet,并将 Excel 文件写入目标文件中。调用此方法时,只需传递源 Excel 文件路径,源 sheet 名称,目标 Excel 文件路径和目标 sheet 名称。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)