1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
| public class CustomColumnWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
private static final int MAX_COLUMN_WIDTH = 255;
private final Map<Integer, Map<Integer, Integer>> cache = MapUtils.newHashMapWithExpectedSize(8);
public CustomColumnWidthStyleStrategy() {}
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
if (needSetWidth) {
Map<Integer, Integer> maxColumnWidthMap = this.cache.computeIfAbsent(writeSheetHolder.getSheetNo(), (key) -> new HashMap<>(16));
double columnWidth = this.dataLength(cellDataList, cell, isHead);
if (columnWidth >= 0) {
if (columnWidth > MAX_COLUMN_WIDTH) {
columnWidth = MAX_COLUMN_WIDTH;
}
Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
maxColumnWidthMap.put(cell.getColumnIndex(), (int) columnWidth);
writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), (int) columnWidth * 256);
}
}
}
}
private double dataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {
if (isHead) {
return getExcelWidth(cell.getStringCellValue());
} else {
WriteCellData<?> cellData = cellDataList.get(0);
CellDataTypeEnum type = cellData.getType();
if (type == null) {
return 0;
} else {
switch (type) {
case STRING:
return this.getExcelWidth(cellData.getStringValue());
case BOOLEAN:
return this.getExcelWidth(cellData.getBooleanValue().toString());
case NUMBER:
return this.getExcelWidth(cellData.getNumberValue().toString());
default:
return 0;
}
}
}
}
/**
* 调整单元格字符字节宽度
*/
private double getExcelWidth(String str) {
double length = 0;
char[] chars = str.toCharArray();
for (char c : chars) {
byte[] bytes = this.getUtf8Bytes(c);
if (bytes.length == 1) {
length += 1.6;
}
if (bytes.length == 2) {
length += 2.2;
}
if (bytes.length == 3) {
length += 3.85;
}
if (bytes.length == 4) {
length += 4.2;
}
}
return length;
}
private byte[] getUtf8Bytes(char c) {
char[] chars = {c};
CharBuffer charBuffer = CharBuffer.allocate(chars.length);
charBuffer.put(chars);
charBuffer.flip();
ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(charBuffer);
return byteBuffer.array();
}
}
|