easyExcel隔行填充
时间: 2023-11-22 07:47:42 浏览: 172
以下是使用easyExcel进行隔行填充的示例代码:
```python
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import java.util.ArrayList;
import java.util.List;
public class EasyExcelDemo {
public static void main(String[] args) {
// 准备数据
List<User> userList = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
User user = new User();
user.setName("user" + i);
user.setAge(i);
userList.add(user);
}
// 配置样式
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
HorizontalCellStyleStrategy horizontalCellStyleStrategy =
new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
// 写入Excel
ExcelWriterBuilder excelWriterBuilder = EasyExcel.write("demo.xlsx", User.class);
ExcelWriterSheetBuilder excelWriterSheetBuilder = excelWriterBuilder.sheet("Sheet1");
excelWriterSheetBuilder.registerWriteHandler(horizontalCellStyleStrategy);
for (int i = 0; i < userList.size(); i++) {
if (i % 2 == 0) {
excelWriterSheetBuilder.doWrite(userList.get(i));
} else {
excelWriterSheetBuilder.fill(userList.get(i));
}
}
// 关闭流
excelWriterBuilder.finish();
}
public static class User {
private String name;
private Integer age;
// 省略getter和setter方法
}
}
```
上述代码中,我们首先准备了一个包含10个用户信息的列表,然后配置了表头和内容的样式,接着使用`ExcelWriterSheetBuilder`的`fill`方法进行隔行填充,最后将数据写入Excel文件中。
阅读全文