HtmlToExcelServer.java
10.3 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package com.bckefu.excel.html;
import com.bckefu.excel.export.style.ExcelExportStylerDefaultImpl;
import com.bckefu.excel.html.css.CssParseServer;
import com.bckefu.excel.html.css.ICssConvertToExcel;
import com.bckefu.excel.html.css.impl.*;
import com.bckefu.excel.html.entity.ExcelCssConstant;
import com.bckefu.excel.html.entity.HtmlCssConstant;
import com.bckefu.excel.html.entity.style.CellStyleEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.RuntimeErrorException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* @author : caoliang
* @date : 2017/11/20 下午3:23
*/
public class HtmlToExcelServer {
private final Logger LOGGER = LoggerFactory
.getLogger(HtmlToExcelServer.class);
//样式
private static final List<ICssConvertToExcel> STYLE_APPLIERS = new LinkedList<ICssConvertToExcel>();
{
STYLE_APPLIERS.add(new AlignCssConvertImpl());
STYLE_APPLIERS.add(new BackgroundCssConvertImpl());
STYLE_APPLIERS.add(new BorderCssConverImpl());
STYLE_APPLIERS.add(new TextCssConvertImpl());
}
//Cell 高宽
private static final List<ICssConvertToExcel> SHEET_APPLIERS = new LinkedList<ICssConvertToExcel>();
{
SHEET_APPLIERS.add(new WidthCssConverImpl());
SHEET_APPLIERS.add(new HeightCssConverImpl());
}
private Sheet sheet;
private Map<String, Object> cellsOccupied = new HashMap<String, Object>();
private Map<String, CellStyle> cellStyles = new HashMap<String, CellStyle>();
private CellStyle defaultCellStyle;
private int maxRow = 0;
private CssParseServer cssParse = new CssParseServer();
// --
// private methods
private void processTable(Element table) {
int rowIndex = 0;
if (maxRow > 0) {
// blank row
maxRow += 2;
rowIndex = maxRow;
}
LOGGER.debug("Interate Table Rows.");
String freezeCol = null;
int freezeColIndex = -1;
for (Element row : table.select("tr")) {
LOGGER.debug("Parse Table Row [{}]. Row Index [{}].", row, rowIndex);
String freezeRow = row.attr(ExcelCssConstant.FREEZE_ROW);
if ("true".equals(freezeRow)) {
sheet.createFreezePane(0, rowIndex + 1, 0, rowIndex + 1);
}
int colIndex = 0;
LOGGER.debug("Interate Cols.");
for (Element td : row.select("td, th")) {
freezeCol = td.attr(ExcelCssConstant.FREEZE_COL);
if ("true".equals(freezeCol)) {
if (colIndex > freezeColIndex) {
freezeColIndex = colIndex;
}
}
// skip occupied cell
while (cellsOccupied.get(rowIndex + "_" + colIndex) != null) {
LOGGER.debug("Cell [{}][{}] Has Been Occupied, Skip.", rowIndex, colIndex);
++colIndex;
}
LOGGER.debug("Parse Col [{}], Col Index [{}].", td, colIndex);
int rowSpan = 0;
String strRowSpan = td.attr("rowspan");
if (StringUtils.isNotBlank(strRowSpan) && StringUtils.isNumeric(strRowSpan)) {
LOGGER.debug("Found Row Span [{}].", strRowSpan);
rowSpan = Integer.parseInt(strRowSpan);
}
int colSpan = 0;
String strColSpan = td.attr("colspan");
if (StringUtils.isNotBlank(strColSpan) && StringUtils.isNumeric(strColSpan)) {
LOGGER.debug("Found Col Span [{}].", strColSpan);
colSpan = Integer.parseInt(strColSpan);
}
// col span & row span
if (colSpan > 1 && rowSpan > 1) {
spanRowAndCol(td, rowIndex, colIndex, rowSpan, colSpan);
colIndex += colSpan;
}
// col span only
else if (colSpan > 1) {
spanCol(td, rowIndex, colIndex, colSpan);
colIndex += colSpan;
}
// row span only
else if (rowSpan > 1) {
spanRow(td, rowIndex, colIndex, rowSpan);
++colIndex;
}
// no span
else {
createCell(td, getOrCreateRow(rowIndex), colIndex).setCellValue(td.text());
++colIndex;
}
}
++rowIndex;
}
if (freezeColIndex != -1) {
sheet.createFreezePane(freezeColIndex + 1, 0, freezeColIndex + 1, 0);
}
}
public Workbook createSheet(String html, Workbook workbook) {
Elements els = Jsoup.parseBodyFragment(html).select("table");
Map<String, Sheet> sheets = new HashMap<String, Sheet>();
Map<String, Integer> maxrowMap = new HashMap<String, Integer>();
for (Element table : els) {
String sheetName = table.attr(ExcelCssConstant.SHEET_NAME);
if (StringUtils.isBlank(sheetName)) {
LOGGER.error("table必须存在name属性!");
throw new RuntimeErrorException(null, "table必须存在name属性");
}
if (sheets.containsKey(sheetName)) {
maxRow = maxrowMap.get(sheetName);
//cellStyles = csStyleMap.get(sheetName);
//cellsOccupied = cellsOccupiedMap.get(sheetName);
sheet = sheets.get(sheetName);
} else {
maxRow = 0;
cellStyles.clear();
cellsOccupied.clear();
sheet = workbook.createSheet(sheetName);
}
//生成一个默认样式
defaultCellStyle = new ExcelExportStylerDefaultImpl(workbook).stringNoneStyle(workbook,
false);
processTable(table);
maxrowMap.put(sheetName, maxRow);
sheets.put(sheetName, sheet);
}
return workbook;
}
private void spanRow(Element td, int rowIndex, int colIndex, int rowSpan) {
LOGGER.debug("Span Row , From Row [{}], Span [{}].", rowIndex, rowSpan);
mergeRegion(rowIndex, rowIndex + rowSpan - 1, colIndex, colIndex);
for (int i = 0; i < rowSpan; ++i) {
Row row = getOrCreateRow(rowIndex + i);
createCell(td, row, colIndex);
cellsOccupied.put((rowIndex + i) + "_" + colIndex, true);
}
getOrCreateRow(rowIndex).getCell(colIndex).setCellValue(td.text());
}
private void spanCol(Element td, int rowIndex, int colIndex, int colSpan) {
LOGGER.debug("Span Col, From Col [{}], Span [{}].", colIndex, colSpan);
mergeRegion(rowIndex, rowIndex, colIndex, colIndex + colSpan - 1);
Row row = getOrCreateRow(rowIndex);
for (int i = 0; i < colSpan; ++i) {
createCell(td, row, colIndex + i);
}
row.getCell(colIndex).setCellValue(td.text());
}
private void spanRowAndCol(Element td, int rowIndex, int colIndex, int rowSpan, int colSpan) {
LOGGER.debug("Span Row And Col, From Row [{}], Span [{}].", rowIndex, rowSpan);
LOGGER.debug("From Col [{}], Span [{}].", colIndex, colSpan);
mergeRegion(rowIndex, rowIndex + rowSpan - 1, colIndex, colIndex + colSpan - 1);
for (int i = 0; i < rowSpan; ++i) {
Row row = getOrCreateRow(rowIndex + i);
for (int j = 0; j < colSpan; ++j) {
createCell(td, row, colIndex + j);
cellsOccupied.put((rowIndex + i) + "_" + (colIndex + j), true);
}
}
getOrCreateRow(rowIndex).getCell(colIndex).setCellValue(td.text());
}
private Cell createCell(Element td, Row row, int colIndex) {
Cell cell = row.getCell(colIndex);
if (cell == null) {
LOGGER.debug("Create Cell [{}][{}].", row.getRowNum(), colIndex);
cell = row.createCell(colIndex);
}
return applyStyle(td, cell);
}
private Cell applyStyle(Element td, Cell cell) {
String style = td.attr(HtmlCssConstant.STYLE);
CellStyle cellStyle = null;
if (StringUtils.isNotBlank(style)) {
CellStyleEntity styleEntity = cssParse.parseStyle(style.trim());
cellStyle = cellStyles.get(styleEntity.toString());
if (cellStyle == null) {
LOGGER.debug("No Cell Style Found In Cache, Parse New Style.");
cellStyle = cell.getRow().getSheet().getWorkbook().createCellStyle();
cellStyle.cloneStyleFrom(defaultCellStyle);
for (ICssConvertToExcel cssConvert : STYLE_APPLIERS) {
cssConvert.convertToExcel(cell, cellStyle, styleEntity);
}
cellStyles.put(styleEntity.toString(), cellStyle);
}
for (ICssConvertToExcel cssConvert : SHEET_APPLIERS) {
cssConvert.convertToExcel(cell, cellStyle, styleEntity);
}
if (cellStyles.size() >= 4000) {
LOGGER.info(
"Custom Cell Style Exceeds 4000, Could Not Create New Style, Use Default Style.");
cellStyle = defaultCellStyle;
}
} else {
LOGGER.debug("Style is null ,Use Default Cell Style.");
cellStyle = defaultCellStyle;
}
cell.setCellStyle(cellStyle);
return cell;
}
private Row getOrCreateRow(int rowIndex) {
Row row = sheet.getRow(rowIndex);
if (row == null) {
LOGGER.debug("Create New Row [{}].", rowIndex);
row = sheet.createRow(rowIndex);
if (rowIndex > maxRow) {
maxRow = rowIndex;
}
}
return row;
}
private void mergeRegion(int firstRow, int lastRow, int firstCol, int lastCol) {
LOGGER.debug("Merge Region, From Row [{}], To [{}].", firstRow, lastRow);
LOGGER.debug("From Col [{}], To [{}].", firstCol, lastCol);
sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
}
}