easyexcel 居中
时间: 2023-07-09 21:33:58 浏览: 154
EasyExcel自定义
你可以使用 EasyExcel 提供的样式设置功能来将单元格居中。具体操作如下:
1. 首先,导入需要使用的类:
```java
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
```
2. 然后,创建一个样式设置对象,并设置单元格水平和垂直居中:
```java
Workbook workbook = WorkbookFactory.create(new File("output.xlsx"));
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
```
3. 最后,使用 EasyExcel 提供的样式策略类来设置单元格样式:
```java
HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(cellStyle, cellStyle);
SimpleColumnWidthStyleStrategy columnWidthStyleStrategy = new SimpleColumnWidthStyleStrategy();
EasyExcel.write("output.xlsx", DemoData.class)
.registerWriteHandler(styleStrategy)
.registerWriteHandler(columnWidthStyleStrategy)
.sheet().doWrite(data());
```
这样,写入 Excel 文件时,单元格的内容就会居中显示了。
阅读全文