CellStyleBuilder.java
package com.alibaba.easyexcel.test;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
/**
* @Author WL
* @Date 2025/2/19 17:18
* @Version 1.0
*/
@Slf4j
@Data
public class CellStyleBuilder {
/**
* 數(shù)值類(lèi)型哟绊,保留整數(shù)
*/
public static final String NUMBER_FORMAT_0 = "0_ ";
/**
* 數(shù)值類(lèi)型顶伞,保留2位小數(shù)
*/
public static final String NUMBER_FORMAT_2 = "0.00_ ";
private Workbook workbook;
private CellStyle cellstyle;
public CellStyleBuilder(Workbook workbook) {
this.workbook = workbook;
this.cellstyle = workbook.createCellStyle();
}
public CellStyle build() {
return cellstyle;
}
public CellStyleBuilder setFont(Object... fontArr) {
Font font = this.workbook.createFont();
try {
for (int i = 0; i < fontArr.length; i++) {
switch (i) {
case 0:
font.setFontName(String.valueOf(fontArr[i]));
continue;
case 1:
font.setFontHeightInPoints(Short.parseShort(String.valueOf(fontArr[1])));
continue;
case 2:
font.setBold(Boolean.parseBoolean(String.valueOf(fontArr[2])));
continue;
default:
log.warn("字體參數(shù)設(shè)置失敗!");
break;
}
}
} catch (Exception e) {
throw new RuntimeException("excel字體設(shè)置失敗!");
}
cellstyle.setFont(font);
return this;
}
public CellStyleBuilder setWrapText(Boolean flag) {
cellstyle.setWrapText(flag);
return this;
}
public CellStyleBuilder setAlignment(HorizontalAlignment horizontalAlignment) {
cellstyle.setAlignment(horizontalAlignment);
return this;
}
public CellStyleBuilder setVerticalAlignment(VerticalAlignment verticalAlignment) {
cellstyle.setVerticalAlignment(verticalAlignment);
return this;
}
public CellStyleBuilder setDataFormat(String format) {
DataFormat dataFormat = this.workbook.createDataFormat();
cellstyle.setDataFormat(dataFormat.getFormat(format));
return this;
}
}
Test.java
package com.alibaba.easyexcel.test.util;
import com.alibaba.easyexcel.test.CellStyleBuilder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* @Author WL
* @Date 2025/2/19 17:32
* @Version 1.0
*/
public class Test {
public static void main(String[] args) {
Workbook workbook = new XSSFWorkbook(); // 或者使用HSSFWorkbook妓美,取決于你的需求
Sheet sheet = workbook.createSheet("Example Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello World");
cell.setCellStyle(new CellStyleBuilder(workbook)
.setFont("宋體", 14, true)
.setWrapText(true)
.setAlignment(HorizontalAlignment.CENTER)
.setVerticalAlignment(VerticalAlignment.CENTER)
.setDataFormat(CellStyleBuilder.NUMBER_FORMAT_2)
.build());
}
}