ExcelToHtmlServer.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package com.bckefu.excel.html;
import com.bckefu.excel.entity.ExcelToHtmlParams;
import com.bckefu.excel.html.helper.CellValueHelper;
import com.bckefu.excel.html.helper.MergedRegionHelper;
import com.bckefu.excel.html.helper.StylerHelper;
import com.bckefu.excel.util.PoiPublicUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author : caoliang
* @date : 2017/11/20 下午3:16
*/
public class ExcelToHtmlServer {
private static final Logger LOGGER = LoggerFactory
.getLogger(ExcelToHtmlServer.class);
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy_MM_dd");
private String today;
private Workbook wb;
private int sheetNum;
private int cssRandom;
/*是不是完成界面*/
private boolean completeHTML;
private Formatter out;
/*已经完成范围处理*/
private boolean gotBounds;
private int firstColumn;
private int endColumn;
private String imageCachePath;
private static final String COL_HEAD_CLASS = "colHeader";
//private static final String ROW_HEAD_CLASS = "rowHeader";
private static final String DEFAULTS_CLASS = "excelDefaults";
//图片缓存
private Map<String, PictureData> pictures = new HashMap<String, PictureData>();
public ExcelToHtmlServer(ExcelToHtmlParams params) {
this.wb = params.getWb();
this.completeHTML = params.isCompleteHTML();
this.sheetNum = params.getSheetNum();
cssRandom = (int) Math.ceil(Math.random() * 1000);
this.imageCachePath = params.getPath();
today = new SimpleDateFormat("yyyy_MM_dd").format(new Date());
}
public String printPage() {
try {
ensureOut();
if (completeHTML) {
out.format("<!DOCTYPE HTML>%n");
out.format("<html>%n");
out.format(
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">%n");
out.format("<head>%n");
}
if (StringUtils.isNotEmpty(imageCachePath)) {
getPictures();
}
new StylerHelper(wb, out, sheetNum, cssRandom);
if (completeHTML) {
out.format("</head>%n");
out.format("<body>%n");
}
print();
if (completeHTML) {
out.format("</body>%n");
out.format("</html>%n");
}
return out.toString();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
} finally {
if (out != null) {
out.close();
}
}
return null;
}
/**
* 获取Sheet缓存的图片
*/
private void getPictures() {
if (wb instanceof XSSFWorkbook) {
pictures = PoiPublicUtil.getSheetPictrues07((XSSFSheet) wb.getSheetAt(sheetNum),
(XSSFWorkbook) wb);
} else {
pictures = PoiPublicUtil.getSheetPictrues03((HSSFSheet) wb.getSheetAt(sheetNum),
(HSSFWorkbook) wb);
}
}
private void print() {
printSheets();
}
private void ensureOut() {
if (out == null) {
out = new Formatter(new StringBuilder());
}
}
private void printSheets() {
Sheet sheet = wb.getSheetAt(sheetNum);
printSheet(sheet);
}
private void printSheet(Sheet sheet) {
out.format("<table class='%s' width='%s'>%n", DEFAULTS_CLASS, getTableWidth(sheet));
printCols(sheet);
printSheetContent(sheet);
out.format("</table>%n");
}
private void printCols(Sheet sheet) {
//out.format("<col/>%n");
ensureColumnBounds(sheet);
for (int i = firstColumn; i < endColumn; i++) {
out.format("<col style='width:%spx;' />%n", sheet.getColumnWidth(i) / 32);
}
}
private int getTableWidth(Sheet sheet) {
ensureColumnBounds(sheet);
int width = 0;
for (int i = firstColumn; i < endColumn; i++) {
width = width + (sheet.getColumnWidth(i) / 32);
}
return width;
}
private void ensureColumnBounds(Sheet sheet) {
if (gotBounds) {
return;
}
Iterator<Row> iter = sheet.rowIterator();
firstColumn = (iter.hasNext() ? Integer.MAX_VALUE : 0);
endColumn = 0;
while (iter.hasNext()) {
Row row = iter.next();
short firstCell = row.getFirstCellNum();
if (firstCell >= 0) {
firstColumn = Math.min(firstColumn, firstCell);
endColumn = Math.max(endColumn, row.getLastCellNum());
}
}
gotBounds = true;
}
@SuppressWarnings("unused")
/**本来是用来生成 A,B 那个列名称的**/
private void printColumnHeads(Sheet sheet) {
out.format("<thead>%n");
out.format(" <tr class=%s>%n", COL_HEAD_CLASS);
out.format(" <th class=%s>◊</th>%n", COL_HEAD_CLASS);
StringBuilder colName = new StringBuilder();
for (int i = firstColumn; i < endColumn; i++) {
colName.setLength(0);
int cnum = i;
do {
colName.insert(0, (char) ('A' + cnum % 26));
cnum /= 26;
} while (cnum > 0);
out.format(" <th class=%s>%s</th>%n", COL_HEAD_CLASS, colName);
}
out.format(" </tr>%n");
out.format("</thead>%n");
}
private void printSheetContent(Sheet sheet) {
//printColumnHeads(sheet);
MergedRegionHelper mergedRegionHelper = new MergedRegionHelper(sheet);
CellValueHelper cellValueHelper = new CellValueHelper(wb, cssRandom);
out.format("<tbody>%n");
Iterator<Row> rows = sheet.rowIterator();
int rowIndex = 1;
while (rows.hasNext()) {
Row row = rows.next();
out.format(" <tr style='height:%spx;'>%n", row.getHeight() / 15);
//out.format(" <td class='%s'>%d</td>%n", ROW_HEAD_CLASS, row.getRowNum() + 1);
for (int i = firstColumn; i < endColumn; i++) {
if (mergedRegionHelper.isNeedCreate(rowIndex, i)) {
String content = " ";
CellStyle style = null;
if (i >= row.getFirstCellNum() && i < row.getLastCellNum()) {
Cell cell = row.getCell(i);
if (cell != null) {
style = cell.getCellStyle();
content = cellValueHelper.getHtmlValue(cell);
}
}
if (pictures.containsKey((rowIndex - 1) + "_" + i)) {
content = "<img src='data:image/" + PoiPublicUtil.getFileExtendName(pictures.get((rowIndex - 1) + "_" + i).getData())
+ ";base64," + getImageSrc(pictures.get((rowIndex - 1) + "_" + i))
+ "' style='max-width: "
+ getImageMaxWidth(
mergedRegionHelper.getRowAndColSpan(rowIndex, i), i, sheet)
+ "px;' />";
}
if (mergedRegionHelper.isMergedRegion(rowIndex, i)) {
Integer[] rowAndColSpan = mergedRegionHelper.getRowAndColSpan(rowIndex, i);
out.format(" <td rowspan='%s' colspan='%s' class='%s' >%s</td>%n",
rowAndColSpan[0], rowAndColSpan[1], styleName(style), content);
} else {
out.format(" <td class='%s'>%s</td>%n", styleName(style), content);
}
}
}
out.format(" </tr>%n");
rowIndex++;
}
out.format("</tbody>%n");
}
/**
* 获取图片最大宽度
*
* @param colIndex
* @param sheet
* @param rowAndColSpan
* @return
*/
private int getImageMaxWidth(Integer[] rowAndColSpan, int colIndex, Sheet sheet) {
if (rowAndColSpan == null) {
return sheet.getColumnWidth(colIndex) / 32;
}
int maxWidth = 0;
for (int i = 0; i < rowAndColSpan[1]; i++) {
maxWidth += sheet.getColumnWidth(colIndex + i) / 32;
}
return maxWidth;
}
/**
* 获取图片路径
*
* @param pictureData
* @return
*/
private String getImageSrc(PictureData pictureData) {
if (pictureData == null) {
return "";
}
byte[] data = pictureData.getData();
//直接输出到HTML使用BASE64Encoder
// 加密
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
/*String fileName = "pic" + Math.round(Math.random() * 100000000000L);
fileName += "." + PoiPublicUtil.getFileExtendName(data);
if (!imageCachePath.startsWith("/") && !imageCachePath.contains(":")) {
imageCachePath = PoiPublicUtil.getWebRootPath(imageCachePath);
}
File savefile = new File(imageCachePath + "/" + today);
if (!savefile.exists()) {
savefile.mkdirs();
}
savefile = new File(imageCachePath + "/" + today + "/" + fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(savefile);
fos.write(data);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
} finally {
try {
fos.close();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
return imageCachePath + "/" + today + "/" + fileName;*/
}
private String styleName(CellStyle style) {
if (style == null) {
return "";
}
return String.format("style_%02x_%s font_%s_%s", style.getIndex(), cssRandom,
style.getFontIndex(), cssRandom);
}
}