EasyExcel修改模板sheet的名称
时间: 2024-05-16 17:14:28 浏览: 227
Java使用Easyexcel批量导入多行表头的Demo.rar
要修改EasyExcel模板中的sheet名称,可以使用`SheetBuilder`类中的`sheetName`方法。具体步骤如下:
1. 使用`EasyExcelFactory`类中的`read`方法读取模板文件,得到`ExcelReader`对象:
```java
ExcelReader excelReader = EasyExcelFactory.read(inputStream).build();
```
2. 使用`excelReader`对象中的`sheetBuilder`方法获取`SheetBuilder`对象,并使用`sheetName`方法设置新的sheet名称:
```java
SheetBuilder sheetBuilder = excelReader.sheetBuilder().sheetNo(sheetIndex);
sheetBuilder.sheetName(newSheetName);
```
其中,`sheetIndex`表示要修改的sheet在Excel文件中的位置,从0开始计数;`newSheetName`表示新的sheet名称。
3. 使用`SheetBuilder`对象中的`build`方法生成新的sheet,并将其写入到目标文件中:
```java
sheetBuilder.build();
excelReader.finish();
```
完整的代码示例:
```java
public static void modifySheetName(String templatePath, String targetPath, int sheetIndex, String newSheetName) throws IOException {
InputStream inputStream = new FileInputStream(templatePath);
ExcelReader excelReader = EasyExcelFactory.read(inputStream).build();
SheetBuilder sheetBuilder = excelReader.sheetBuilder().sheetNo(sheetIndex);
sheetBuilder.sheetName(newSheetName);
sheetBuilder.build();
excelReader.finish();
FileOutputStream outputStream = new FileOutputStream(targetPath);
Workbook workbook = excelReader.getWorkbook();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
```
调用示例:
```java
String templatePath = "template.xlsx";
String targetPath = "target.xlsx";
int sheetIndex = 0;
String newSheetName = "New Sheet";
modifySheetName(templatePath, targetPath, sheetIndex, newSheetName);
```
阅读全文