excel转html实现在线预览
⾸先说⼀下,本⼈发布的代码都是经过本⼈亲测,并且⽤在实际项⽬中。如果觉得可以,希望⼤家点个赞,谢谢⼤家。
有什么问题,⼤家评论出来,⼀起交流。好了,不废话了,下⾯来说⼀说这个东西怎么做。
我采⽤poi去做这个功能,虽然还有jxl等其它⽅式,其它⽅式都有⼤的缺陷,有的不⽀持excel07版本,有的不能跨平台使⽤,这些都是很致命的缺点。
所以我采⽤poi去研究,我测试office和wps的excel版本都⽀持,并且兼容excel03及07以后版本,效果达到我的要求了,下⾯贴出源码,供⼤家⼀起学习。
jar包主要是这些
1
DecimalFormat;
SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
pdf转htmlimport org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
2
3 * @param filePath excel源⽂件⽂件的路径
4 * @param htmlPositon ⽣成的html⽂件的路径
5 * @param isWithStyle 是否需要表格样式包含字体颜⾊边框对齐⽅式
6
7*/
8public static String readExcelToHtml(String filePath ,String htmlPositon, boolean isWithStyle){
9
10 InputStream is = null;
11 String htmlExcel = null;
12try {
13 File sourcefile = new File(filePath);
14 is = new FileInputStream(sourcefile);
15 Workbook wb = ate(is);
16if (wb instanceof XSSFWorkbook) { //03版excel处理⽅法
17 XSSFWorkbook xWb = (XSSFWorkbook) wb;
18 htmlExcel = ExcelInfo(xWb,isWithStyle);
19 }else if(wb instanceof HSSFWorkbook){ //07及10版以后的excel处理⽅法
20 HSSFWorkbook hWb = (HSSFWorkbook) wb;
21 htmlExcel = ExcelInfo(hWb,isWithStyle);
22 }
23 writeFile(htmlExcel,htmlPositon);
24 } catch (Exception e) {
25 e.printStackTrace();
26 }finally{
27try {
28 is.close();
29 } catch (IOException e) {
30 e.printStackTrace();
31 }
32 }
33return htmlPositon;
34 }
35
36
37
38private static String getExcelInfo(Workbook wb,boolean isWithStyle){
39
40 StringBuffer sb = new StringBuffer();
41 Sheet sheet = wb.getSheetAt(0);//获取第⼀个Sheet的内容
42int lastRowNum = LastRowNum();
43 Map<String, String> map[] = getRowSpanColSpanMap(sheet);
44 sb.append("<table style='border-collapse:collapse;' width='100%'>");
45 Row row = null; //兼容
46 Cell cell = null; //兼容
47
48for (int rowNum = FirstRowNum(); rowNum <= lastRowNum; rowNum++) { 49 row = Row(rowNum);
50if (row == null) {
51 sb.append("<tr><td ><nobr> </nobr></td></tr>");
52continue;
53 }
54 sb.append("<tr>");
55int lastColNum = LastCellNum();
56for (int colNum = 0; colNum < lastColNum; colNum++) {
57 cell = Cell(colNum);
58if (cell == null) { //特殊情况空⽩的单元格会返回null
59 sb.append("<td> </td>");
60continue;
61 }
62
63 String stringValue = getCellValue(cell);
64if (map[0].containsKey(rowNum + "," + colNum)) {
65 String pointString = map[0].get(rowNum + "," + colNum);
66 map[0].remove(rowNum + "," + colNum);
67int bottomeRow = Integer.valueOf(pointString.split(",")[0]);
68int bottomeCol = Integer.valueOf(pointString.split(",")[1]);
69int rowSpan = bottomeRow - rowNum + 1;
70int colSpan = bottomeCol - colNum + 1;
71 sb.append("<td rowspan= '" + rowSpan + "' colspan= '"+ colSpan + "' ");
72 } else if (map[1].containsKey(rowNum + "," + colNum)) {
73 map[1].remove(rowNum + "," + colNum);
74continue;
75 } else {
76 sb.append("<td ");
77 }
78
79//判断是否需要样式
80if(isWithStyle){
81 dealExcelStyle(wb, sheet, cell, sb);//处理单元格样式
82 }
83
84 sb.append("><nobr>");
85if (stringValue == null || "".im())) {
86 sb.append(" ");
87 } else {
88// 将ascii码为160的空格转换为html下的空格()
89 sb.place(String.valueOf((char) 160)," "));
90 }
91 sb.append("</nobr></td>");
92 }
93 sb.append("</tr>");
94 }
95
96 sb.append("</table>");
String();
98 }
99
100private static Map<String, String>[] getRowSpanColSpanMap(Sheet sheet) {
101
102 Map<String, String> map0 = new HashMap<String, String>();
103 Map<String, String> map1 = new HashMap<String, String>();
104int mergedNum = NumMergedRegions();
105 CellRangeAddress range = null;
106for (int i = 0; i < mergedNum; i++) {
107 range = MergedRegion(i);
108int topRow = FirstRow();
109int topCol = FirstColumn();
110int bottomRow = LastRow();
111int bottomCol = LastColumn();
112 map0.put(topRow + "," + topCol, bottomRow + "," + bottomCol);
113// System.out.println(topRow + "," + topCol + "," + bottomRow + "," + bottomCol); 114int tempRow = topRow;
115while (tempRow <= bottomRow) {
116int tempCol = topCol;
117while (tempCol <= bottomCol) {
118 map1.put(tempRow + "," + tempCol, "");
119 tempCol++;
120 }
121 tempRow++;
122 }
123 ve(topRow + "," + topCol);
124 }
125 Map[] map = { map0, map1 };
126return map;
127 }
128
129
130/**
131 * 获取表格单元格Cell内容
132 * @param cell
133 * @return
134*/
135private static String getCellValue(Cell cell) {
136
137 String result = new String();
138switch (CellType()) {
139case Cell.CELL_TYPE_NUMERIC:// 数字类型
140if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理⽇期格式、时间格式
141 SimpleDateFormat sdf = null;
142if (CellStyle().getDataFormat() == BuiltinFormat("h:mm")) {
143 sdf = new SimpleDateFormat("HH:mm");
144 } else {// ⽇期
145 sdf = new SimpleDateFormat("yyyy-MM-dd");
146 }
147 Date date = DateCellValue();
148 result = sdf.format(date);
149 } else if (CellStyle().getDataFormat() == 58) {
150// 处理⾃定义⽇期格式:m⽉d⽇(通过判断单元格的格式id解决,id的值是58)
151 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
152double value = NumericCellValue();
153 Date date = org.apache.poi.ss.usermodel.DateUtil
154 .getJavaDate(value);
155 result = sdf.format(date);
156 } else {
157double value = NumericCellValue();
158 CellStyle style = CellStyle();
159 DecimalFormat format = new DecimalFormat();
160 String temp = DataFormatString();
161// 单元格设置成常规
162if (temp.equals("General")) {
163 format.applyPattern("#");
164 }
165 result = format.format(value);
166 }
167break;
168case Cell.CELL_TYPE_STRING:// String类型
169 result = RichStringCellValue().toString();
170break;
171case Cell.CELL_TYPE_BLANK:
172 result = "";
173break;
174default:
175 result = "";
176break;
177 }
178return result;
179 }
180
181/**
182 * 处理表格样式
183 * @param wb
184 * @param sheet
185 * @param sb
186*/
187private static void dealExcelStyle(Workbook wb,Sheet sheet,Cell cell,StringBuffer sb){
188
189 CellStyle cellStyle = CellStyle();
190if (cellStyle != null) {
191short alignment = Alignment();
192// sb.append("align='" + convertAlignToHtml(alignment) + "' ");//单元格内容的⽔平对齐⽅式
193short verticalAlignment = VerticalAlignment();
194 sb.append("valign='"+ convertVerticalAlignToHtml(verticalAlignment)+ "' ");//单元格中内容的垂直排列⽅式195
196if (wb instanceof XSSFWorkbook) {
197
198 XSSFFont xf = ((XSSFCellStyle) cellStyle).getFont();
199short boldWeight = xf.getBoldweight();
200 String align = convertAlignToHtml(alignment);
201 sb.append("style='");
202 sb.append("font-weight:" + boldWeight + ";"); // 字体加粗
203 sb.append("font-size: " + xf.getFontHeight() / 2 + "%;"); // 字体⼤⼩
204int columnWidth = ColumnIndex()) ;
205 sb.append("width:" + columnWidth + "px;");
206 sb.append("text-align:" + align + ";");//表头排版样式
207 XSSFColor xc = xf.getXSSFColor();
208if (xc != null && !"".equals(xc)) {
209 sb.append("color:#" + xc.getARGBHex().substring(2) + ";"); // 字体颜⾊
210 }
211
212 XSSFColor bgColor = (XSSFColor) FillForegroundColorColor();
213if (bgColor != null && !"".equals(bgColor)) {
214 sb.append("background-color:#" + ARGBHex().substring(2) + ";"); // 背景颜⾊
215 }
216 sb.append(getBorderStyle(BorderTop(), ((XSSFCellStyle) cellStyle).getTopBorderXSSFColor()));
217 sb.append(getBorderStyle(BorderRight(), ((XSSFCellStyle) cellStyle).getRightBorderXSSFColor())); 218 sb.append(getBorderStyle(BorderBottom(), ((XSSFCellStyle) cellStyle).getBottomBorderXSSFColor())); 219 sb.append(getBorderStyle(BorderLeft(), ((XSSFCellStyle) cellStyle).getLeftBorderXSSFColor()));
220
221 }else if(wb instanceof HSSFWorkbook){
222
223 HSSFFont hf = ((HSSFCellStyle) cellStyle).getFont(wb);
224short boldWeight = hf.getBoldweight();
225short fontColor = hf.getColor();
226 sb.append("style='");
227 HSSFPalette palette = ((HSSFWorkbook) wb).getCustomPalette(); // 类HSSFPalette⽤于求的颜⾊的国际标准形式228 HSSFColor hc = Color(fontColor);
229 sb.append("font-weight:" + boldWeight + ";"); // 字体加粗
230 sb.append("font-size: " + hf.getFontHeight() / 2 + "%;"); // 字体⼤⼩
231 String align = convertAlignToHtml(alignment);
232 sb.append("text-align:" + align + ";");//表头排版样式
233 String fontColorStr = convertToStardColor(hc);
234if (fontColorStr != null && !"".im())) {
235 sb.append("color:" + fontColorStr + ";"); // 字体颜⾊
236 }
237int columnWidth = ColumnIndex()) ;
238 sb.append("width:" + columnWidth + "px;");
239short bgColor = FillForegroundColor();
240 hc = Color(bgColor);
241 String bgColorStr = convertToStardColor(hc);
242if (bgColorStr != null && !"".im())) {
243 sb.append("background-color:" + bgColorStr + ";"); // 背景颜⾊
244 }
245 sb.append( getBorderStyle(palette,BorderTop(),TopBorderColor()));
246 sb.append( getBorderStyle(palette,BorderRight(),RightBorderColor()));
247 sb.append( getBorderStyle(palette,BorderLeft(),LeftBorderColor()));
248 sb.append( getBorderStyle(palette,BorderBottom(),BottomBorderColor()));
249 }
250
251 sb.append("' ");
252 }
253 }
254
255/**
256 * 单元格内容的⽔平对齐⽅式
257 * @param alignment
258 * @return
259*/
260private static String convertAlignToHtml(short alignment) {
261
262 String align = "center";
263switch (alignment) {
264case CellStyle.ALIGN_LEFT:
265 align = "left";
266break;
267case CellStyle.ALIGN_CENTER:
268 align = "center";
269break;
270case CellStyle.ALIGN_RIGHT:
271 align = "right";
272break;
273default:
274break;
275 }
276return align;
277 }
278
279/**
280 * 单元格中内容的垂直排列⽅式
281 * @param verticalAlignment
282 * @return
283*/
284private static String convertVerticalAlignToHtml(short verticalAlignment) {
285
286 String valign = "middle";
287switch (verticalAlignment) {
288case CellStyle.VERTICAL_BOTTOM:
289 valign = "bottom";
290break;
291case CellStyle.VERTICAL_CENTER:
292 valign = "center";
293break;
294case CellStyle.VERTICAL_TOP:
295 valign = "top";
296break;
297default:
298break;
299 }
300return valign;
301 }
302
303private static String convertToStardColor(HSSFColor hc) {
304
305 StringBuffer sb = new StringBuffer("");
306if (hc != null) {
307if (HSSFColor.AUTOMATIC.index == hc.getIndex()) {
308return null;
309 }
310 sb.append("#");
311for (int i = 0; i < hc.getTriplet().length; i++) {
312 sb.append(Triplet()[i])));
313 }
314 }
315
String();
317 }
318
319private static String fillWithZero(String str) {
320if (str != null && str.length() < 2) {
321return "0" + str;
322 }
323return str;
324 }
325
326static String[] bordesr={"border-top:","border-right:","border-bottom:","border-left:"};
327static String[] borderStyles={"solid ","solid ","solid ","solid ","solid ","solid ","solid ","solid ","solid ","solid","solid","solid","solid","solid"};
328
329private static String getBorderStyle( HSSFPalette palette ,int b,short s, short t){
330
331if(s==0)return bordesr[b]+borderStyles[s]+"#d0d7e5 1px;";;
332 String borderColorStr = convertToStardColor( Color(t));
333 borderColorStr=borderColorStr==null|| borderColorStr.length()<1?"#000000":borderColorStr;
334return bordesr[b]+borderStyles[s]+borderColorStr+" 1px;";
335
336 }
337
338private static String getBorderStyle(int b,short s, XSSFColor xc){
339
340if(s==0)return bordesr[b]+borderStyles[s]+"#d0d7e5 1px;";;
341if (xc != null && !"".equals(xc)) {
342 String borderColorStr = xc.getARGBHex();//t.getARGBHex();
343 borderColorStr=borderColorStr==null|| borderColorStr.length()<1?"#000000":borderColorStr.substring(2);
344return bordesr[b]+borderStyles[s]+borderColorStr+" 1px;";
345 }
346
347return "";
348 }
349/*
350 * @param content ⽣成的excel表格标签
351 * @param htmlPath ⽣成的html⽂件地址
352*/
353private static void writeFile(String content,String htmlPath){
354 File file2 = new File(htmlPath);
355 StringBuilder sb = new StringBuilder();
356try {
357 ateNewFile();//创建⽂件
358
359 sb.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=GBK\"><title>Html Test</title></head><body>"); 360 sb.append("<div>");
361 sb.append(content);
362 sb.append("</div>");
363 sb.append("</body></html>");
364
365 PrintStream printStream = new PrintStream(new FileOutputStream(file2));
366
367 printStream.String());//将字符串写⼊⽂件
368
发布评论