JAVA-读取excel转成html 将excel表格转换为HTML文件格式 转成前端表格样式

太过爱你忘了你带给我的痛 2024-03-31 14:59 179阅读 0赞

文章目录

    • 1、调用函数
    • 2、excel转html工具类
    • 3、html样式解析
        • 3.1 加载图片-URL链接
        • 3.2 设置图片大小
        • 3.3 设置标题-底色&加粗
        • 3.4 圆点样式
        • 3.5 url链接显示为设置内容
        • 3.6 表格 — 一行三列
        • 3.6 表格 — 两行三列
        • 3.7 段落
    • 4、时间工具类

博客背景:JAVA项目,将Excel转换为HTML的便捷工具类。可快速上手使用~

1、调用函数

excelPositon为存放excel的位置;htmlPositon为将要存放html的位置。
可以直接设置位置为磁盘中指定位置;如下默认为项目运行的上一级目录

  1. public void excel2Html() {
  2. String excelPositon = "../test.xlsx";
  3. String htmlPositon = "../test.html";
  4. //excel转html;src为excel位置,htmlPositon为存放html文件位置
  5. Excel2HtmlUtil.readExcelToHtml(excelPositon, htmlPositon, true, "xlsx", "test");
  6. }

2、excel转html工具类

创建相应工具类Excel2HtmlUtil
改编了一些表头、第一列的样式;还有链接时的样式。如无需可以在对应位置去掉即可~
调用函数readExcelToHtml()可直接使用转换~

  1. //excel转html工具类
  2. package com.xx.util;
  3. import org.apache.commons.io.FileUtils;
  4. import org.apache.poi.hssf.usermodel.*;
  5. import org.apache.poi.hssf.util.HSSFColor;
  6. import org.apache.poi.ss.usermodel.*;
  7. import org.apache.poi.ss.util.CellRangeAddress;
  8. import org.apache.poi.xssf.usermodel.XSSFCellStyle;
  9. import org.apache.poi.xssf.usermodel.XSSFColor;
  10. import org.apache.poi.xssf.usermodel.XSSFFont;
  11. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  12. import java.io.*;
  13. import java.text.DecimalFormat;
  14. import java.text.SimpleDateFormat;
  15. import java.util.*;
  16. import java.util.regex.Matcher;
  17. import java.util.regex.Pattern;
  18. public class Excel2HtmlUtil {
  19. /**
  20. *
  21. * @param filePath excel源文件文件的路径
  22. * @param htmlPositon 生成的html文件的路径
  23. * @param isWithStyle 是否需要表格样式 包含 字体 颜色 边框 对齐方式
  24. * @throws Exception
  25. *
  26. */
  27. public static String readExcelToHtml(String filePath, String htmlPositon, boolean isWithStyle,String type,String attname) throws Exception {
  28. InputStream is = null;
  29. String htmlExcel = null;
  30. Map<String,String> stylemap = new HashMap<String,String>();
  31. try {
  32. if("csv".equalsIgnoreCase(type)) {
  33. htmlExcel = getCSVInfo(filePath,htmlPositon);
  34. writeFile1(htmlExcel, htmlPositon,stylemap,attname);
  35. }else {
  36. File sourcefile = new File(filePath);
  37. is = new FileInputStream(sourcefile);
  38. Workbook wb = WorkbookFactory.create(is);
  39. if (wb instanceof XSSFWorkbook) {
  40. // 03版excel处理方法
  41. XSSFWorkbook xWb = (XSSFWorkbook) wb;
  42. htmlExcel = getExcelInfo(xWb, isWithStyle,stylemap);
  43. } else if (wb instanceof HSSFWorkbook) {
  44. // 07及10版以后的excel处理方法
  45. HSSFWorkbook hWb = (HSSFWorkbook) wb;
  46. htmlExcel = getExcelInfo(hWb, isWithStyle,stylemap);
  47. }
  48. writeFile(htmlExcel, htmlPositon,stylemap,attname);
  49. }
  50. } catch (Exception e) {
  51. System.out.println("文件被损坏或不能打开,无法预览");
  52. //throw new Exception("文件被损坏或不能打开,无法预览");
  53. } finally {
  54. try {
  55. if(is!=null){
  56. is.close();
  57. }
  58. } catch (IOException e) {
  59. e.printStackTrace();
  60. }
  61. }
  62. return htmlPositon;
  63. }
  64. private static void getcscvvalue(BufferedReader reader,List col,String oldvalue,List list) {
  65. String line = null;
  66. try {
  67. while((line=reader.readLine())!=null){
  68. String[] item = line.split(",",-1);
  69. boolean isbreak = false;
  70. for(int i=0;i<item.length;i++) {
  71. String value = item[i];
  72. if(value.endsWith("\"")) {
  73. value = oldvalue+value;
  74. col.add(value);
  75. }else if(item.length==1) {
  76. value = oldvalue+value;
  77. getcscvvalue(reader,col,value,list);
  78. isbreak = true;
  79. }else if(value.startsWith("\"")){
  80. getcscvvalue(reader,col,value,list);
  81. isbreak = true;
  82. }else {
  83. col.add(value);
  84. }
  85. }
  86. if(!isbreak) {
  87. list.add(col);
  88. col = new ArrayList();
  89. }
  90. }
  91. } catch (IOException e) {
  92. }
  93. }
  94. private static String getCSVInfo(String filePath,String htmlPositon) {
  95. StringBuffer sb = new StringBuffer();
  96. DataInputStream in = null;
  97. try {
  98. in=new DataInputStream(new FileInputStream(filePath));
  99. BufferedReader reader=new BufferedReader(new InputStreamReader(in));
  100. //reader.readLine();
  101. String line = null;
  102. List list = new ArrayList();
  103. while((line=reader.readLine())!=null){
  104. String[] item = line.split(",");
  105. List col = new ArrayList();
  106. for(int i=0;i<item.length;i++) {
  107. String value = item[i];
  108. if(value.startsWith("\"")) {
  109. getcscvvalue(reader,col,value,list);
  110. }else {
  111. col.add(value);
  112. }
  113. }
  114. list.add(col);
  115. }
  116. sb.append("<table>");
  117. for(int i=0;i<list.size();i++) {
  118. List col = (List) list.get(i);
  119. if(col==null||col.size()==0) {
  120. sb.append("<tr><td ></td></tr>");
  121. }
  122. sb.append("<tr>");
  123. for(int j=0;j<col.size();j++) {
  124. String value = (String) col.get(j);
  125. if (value == null||"".equals(value)) {
  126. sb.append("<td> </td>");
  127. continue;
  128. }else {
  129. sb.append("<td>"+value+"</td>");
  130. }
  131. }
  132. sb.append("</tr>");
  133. }
  134. sb.append("</table>");
  135. } catch (IOException e) {
  136. // TODO Auto-generated catch block
  137. e.printStackTrace();
  138. } finally {
  139. try {
  140. in.close();
  141. } catch (IOException e) {
  142. e.printStackTrace();
  143. }
  144. }
  145. return sb.toString();
  146. }
  147. //读取excel文件,返回转换后的html字符串
  148. private static String getExcelInfo(Workbook wb, boolean isWithStyle, Map<String,String> stylemap) {
  149. StringBuffer sb = new StringBuffer();
  150. StringBuffer ulsb = new StringBuffer();
  151. ulsb.append("<ul>");
  152. int num = wb.getNumberOfSheets();
  153. //遍历excel文件里的每一个sheet
  154. for(int i=0;i<num;i++) {
  155. Sheet sheet = wb.getSheetAt(i);// 获取第i个Sheet的内容
  156. String sheetName = sheet.getSheetName();
  157. if(i==0) {
  158. //ulsb.append("<li id='li_"+i+"' class='cur' οnclick='changetab("+i+")'>"+sheetName+"</li>");
  159. ulsb.append("<h3 style=\"background-color:LightSkyBlue ;\">" + sheetName + "</h3>");
  160. }else {
  161. //sheet名字 加上了蓝色底色
  162. //ulsb.append("<li id='li_"+i+"' οnclick='changetab("+i+")'>"+sheetName+"</li>");
  163. ulsb.append("<h3 style=\"background-color:LightSkyBlue ;\">" + sheetName + "</h3>");
  164. }
  165. int lastRowNum = sheet.getLastRowNum();
  166. Map<String, String> map[] = getRowSpanColSpanMap(sheet);
  167. Map<String, String> map1[] = getRowSpanColSpanMap(sheet);
  168. sb.append("<table id='table_"+i+"' ");
  169. if(i==0) {
  170. sb.append("class='block'");
  171. }
  172. sb.append(">");
  173. Row row = null; // 兼容
  174. Cell cell = null; // 兼容
  175. int maxRowNum = 0;
  176. int maxColNum = 0;
  177. //遍历每一行
  178. for (int rowNum = sheet.getFirstRowNum(); rowNum <= lastRowNum; rowNum++) {
  179. row = sheet.getRow(rowNum);
  180. if (row == null) {
  181. continue;
  182. }
  183. int lastColNum = row.getLastCellNum();
  184. for (int colNum = 0; colNum < lastColNum; colNum++) {
  185. cell = row.getCell(colNum);
  186. if (cell == null) {
  187. // 特殊情况 空白的单元格会返回null
  188. continue;
  189. }
  190. String stringValue = getCellValue1(cell);
  191. if (map1[0].containsKey(rowNum + "," + colNum)) {
  192. map1[0].remove(rowNum + "," + colNum);
  193. if(maxRowNum<rowNum) {
  194. maxRowNum = rowNum;
  195. }
  196. if(maxColNum<colNum) {
  197. maxColNum = colNum;
  198. }
  199. } else if (map1[1].containsKey(rowNum + "," + colNum)) {
  200. map1[1].remove(rowNum + "," + colNum);
  201. if(maxRowNum<rowNum) {
  202. maxRowNum = rowNum;
  203. }
  204. if(maxColNum<colNum) {
  205. maxColNum = colNum;
  206. }
  207. continue;
  208. }
  209. if (stringValue == null || "".equals(stringValue.trim())) {
  210. continue;
  211. }else {
  212. if(maxRowNum<rowNum) {
  213. maxRowNum = rowNum;
  214. }
  215. if(maxColNum<colNum) {
  216. maxColNum = colNum;
  217. }
  218. }
  219. }
  220. }
  221. for (int rowNum = sheet.getFirstRowNum(); rowNum <= maxRowNum; rowNum++) {
  222. row = sheet.getRow(rowNum);
  223. if (row == null) {
  224. sb.append("<tr><td ></td></tr>");
  225. continue;
  226. }
  227. sb.append("<tr>");
  228. int lastColNum = row.getLastCellNum();
  229. for (int colNum = 0; colNum <= maxColNum; colNum++) {
  230. cell = row.getCell(colNum);
  231. if (cell == null) {
  232. // 特殊情况 空白的单元格会返回null
  233. sb.append("<td> </td>");
  234. continue;
  235. }
  236. String stringValue = getCellValue(cell);
  237. if (stringValue.equals("")) {
  238. // 空字符串返空
  239. sb.append(stringValue.replace(String.valueOf((char) 160), " "));
  240. }
  241. String pattrenStr = "[a-zA-z]+://[^\\s]*";
  242. Pattern pattern = Pattern.compile(pattrenStr);
  243. Matcher matcher = pattern.matcher(stringValue);
  244. if (map[0].containsKey(rowNum + "," + colNum)) {
  245. String pointString = map[0].get(rowNum + "," + colNum);
  246. map[0].remove(rowNum + "," + colNum);
  247. int bottomeRow = Integer.valueOf(pointString.split(",")[0]);
  248. int bottomeCol = Integer.valueOf(pointString.split(",")[1]);
  249. int rowSpan = bottomeRow - rowNum + 1;
  250. int colSpan = bottomeCol - colNum + 1;
  251. if(rowNum == 0){
  252. sb.append("<td style=\"background-color:WhiteSmoke;font-weight:bold;\",rowspan= '" + rowSpan + "' colspan= '" + colSpan + "' ");
  253. }else{
  254. sb.append("<td rowspan= '" + rowSpan + "' colspan= '" + colSpan + "' ");
  255. }
  256. } else if (map[1].containsKey(rowNum + "," + colNum)) {
  257. map[1].remove(rowNum + "," + colNum);
  258. continue;
  259. } else {
  260. if(rowNum == 0 || colNum == 0){
  261. //列表头加粗&底色
  262. sb.append("<td style=\"background-color:WhiteSmoke;font-weight:bold;\"");
  263. }else{
  264. sb.append("<td ");
  265. }
  266. }
  267. if (isWithStyle) {
  268. dealExcelStyle(wb, sheet, cell, sb,stylemap);// 处理单元格样式
  269. }
  270. sb.append("><nobr>");
  271. //如果单元格为空要判断该单元格是不是通过其他单元格计算得到的
  272. if (stringValue == null) {
  273. // if (stringValue == null || "".equals(stringValue.trim())) {
  274. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  275. if (evaluator.evaluate(cell) != null) {
  276. //如果单元格的值是通过其他单元格计算来的,则通过单元格计算获取
  277. String cellnumber = evaluator.evaluate(cell).getNumberValue() + "";
  278. //如果单元格的值是小数,保留两位
  279. if (null != cellnumber && cellnumber.contains(".")) {
  280. String[] decimal = cellnumber.split("\\.");
  281. if (decimal[1].length() > 2) {
  282. int num1 = decimal[1].charAt(0) - '0';
  283. int num2 = decimal[1].charAt(1) - '0';
  284. int num3 = decimal[1].charAt(2) - '0';
  285. if (num3 == 9) {
  286. num2 = 0;
  287. } else if (num3 >= 5) {
  288. num2 = num2 + 1;
  289. }
  290. cellnumber = decimal[0] + "." + num1 + num2;
  291. }
  292. }
  293. stringValue = cellnumber;
  294. }
  295. sb.append(stringValue.replace(String.valueOf((char) 160), " "));
  296. } else {
  297. //如果是链接则使用该语句
  298. if(matcher.matches()){
  299. sb.append("<a href=\""+ stringValue + "\">点击查看内容</a>");
  300. }else{
  301. // 将ascii码为160的空格转换为html下的空格( )
  302. sb.append(stringValue.replace(String.valueOf((char) 160), " "));
  303. }
  304. }
  305. sb.append("</nobr></td>");
  306. }
  307. sb.append("</tr>");
  308. }
  309. sb.append("</table>");
  310. }
  311. ulsb.append("</ul>");
  312. return ulsb.toString()+sb.toString();
  313. }
  314. private static Map<String, String>[] getRowSpanColSpanMap(Sheet sheet) {
  315. Map<String, String> map0 = new HashMap<String, String>();
  316. Map<String, String> map1 = new HashMap<String, String>();
  317. int mergedNum = sheet.getNumMergedRegions();
  318. CellRangeAddress range = null;
  319. for (int i = 0; i < mergedNum; i++) {
  320. range = sheet.getMergedRegion(i);
  321. int topRow = range.getFirstRow();
  322. int topCol = range.getFirstColumn();
  323. int bottomRow = range.getLastRow();
  324. int bottomCol = range.getLastColumn();
  325. map0.put(topRow + "," + topCol, bottomRow + "," + bottomCol);
  326. // System.out.println(topRow + "," + topCol + "," + bottomRow + "," +
  327. // bottomCol);
  328. int tempRow = topRow;
  329. while (tempRow <= bottomRow) {
  330. int tempCol = topCol;
  331. while (tempCol <= bottomCol) {
  332. map1.put(tempRow + "," + tempCol, "");
  333. tempCol++;
  334. }
  335. tempRow++;
  336. }
  337. map1.remove(topRow + "," + topCol);
  338. }
  339. Map[] map = {
  340. map0, map1 };
  341. return map;
  342. }
  343. private static String getCellValue1(Cell cell) {
  344. String result = new String();
  345. switch (cell.getCellType()) {
  346. case NUMERIC:// 数字类型
  347. result = "1";
  348. break;
  349. case STRING:// String类型
  350. result = "1";
  351. break;
  352. case BLANK:
  353. result = "";
  354. break;
  355. default:
  356. result = "";
  357. break;
  358. }
  359. return result;
  360. }
  361. /**
  362. * 获取表格单元格Cell内容
  363. *
  364. * @param cell
  365. * @return
  366. */
  367. private static String getCellValue(Cell cell) {
  368. String result = new String();
  369. switch (cell.getCellType()) {
  370. case NUMERIC:// 数字类型
  371. if (DateUtil.isCellDateFormatted(cell)) {
  372. // 处理日期格式、时间格式
  373. SimpleDateFormat sdf = null;
  374. if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
  375. sdf = new SimpleDateFormat("HH:mm");
  376. } else {
  377. // 日期
  378. sdf = new SimpleDateFormat("yyyy-MM-dd");
  379. }
  380. Date date = cell.getDateCellValue();
  381. result = sdf.format(date);
  382. } else if (cell.getCellStyle().getDataFormat() == 58) {
  383. // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
  384. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  385. double value = cell.getNumericCellValue();
  386. Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
  387. result = sdf.format(date);
  388. } else {
  389. double value = cell.getNumericCellValue();
  390. CellStyle style = cell.getCellStyle();
  391. DecimalFormat format = new DecimalFormat();
  392. String temp = style.getDataFormatString();
  393. // 单元格设置成常规
  394. if (temp.equals("General")) {
  395. format.applyPattern("#");
  396. }
  397. result = format.format(value);
  398. }
  399. break;
  400. case STRING:// String类型
  401. result = cell.getRichStringCellValue().toString();
  402. break;
  403. case BLANK:
  404. result = "";
  405. break;
  406. default:
  407. result = "";
  408. break;
  409. }
  410. return result;
  411. }
  412. /**
  413. * 处理表格样式
  414. *
  415. * @param wb
  416. * @param sheet
  417. * @param sb
  418. */
  419. private static void dealExcelStyle(Workbook wb, Sheet sheet, Cell cell, StringBuffer sb,Map<String,String> stylemap) {
  420. CellStyle cellStyle = cell.getCellStyle();
  421. if (cellStyle != null) {
  422. HorizontalAlignment alignment = cellStyle.getAlignment();
  423. // sb.append("align='" + convertAlignToHtml(alignment) + "' ");//单元格内容的水平对齐方式
  424. VerticalAlignment verticalAlignment = cellStyle.getVerticalAlignment();
  425. String _style = "vertical-align:"+convertVerticalAlignToHtml(verticalAlignment)+";";
  426. if (wb instanceof XSSFWorkbook) {
  427. XSSFFont xf = ((XSSFCellStyle) cellStyle).getFont();
  428. //short boldWeight = xf.getBoldweight();
  429. short boldWeight = 400;
  430. String align = convertAlignToHtml(alignment);
  431. int columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
  432. _style +="font-weight:" + boldWeight + ";font-size: " + xf.getFontHeight() / 2 + "%;width:" + columnWidth + "px;text-align:" + align + ";";
  433. XSSFColor xc = xf.getXSSFColor();
  434. if (xc != null && !"".equals(xc)) {
  435. _style +="color:#" + xc.getARGBHex().substring(2) + ";";
  436. }
  437. XSSFColor bgColor = (XSSFColor) cellStyle.getFillForegroundColorColor();
  438. if (bgColor != null && !"".equals(bgColor)) {
  439. _style +="background-color:#" + bgColor.getARGBHex().substring(2) + ";"; // 背景颜色
  440. }
  441. _style +=getBorderStyle(0, cellStyle.getBorderTop().getCode(),((XSSFCellStyle) cellStyle).getTopBorderXSSFColor());
  442. _style +=getBorderStyle(1, cellStyle.getBorderRight().getCode(),((XSSFCellStyle) cellStyle).getRightBorderXSSFColor());
  443. _style +=getBorderStyle(2, cellStyle.getBorderBottom().getCode(),((XSSFCellStyle) cellStyle).getBottomBorderXSSFColor());
  444. _style +=getBorderStyle(3, cellStyle.getBorderLeft().getCode(),((XSSFCellStyle) cellStyle).getLeftBorderXSSFColor());
  445. } else if (wb instanceof HSSFWorkbook) {
  446. HSSFFont hf = ((HSSFCellStyle) cellStyle).getFont(wb);
  447. short boldWeight = hf.getFontHeight();
  448. short fontColor = hf.getColor();
  449. HSSFPalette palette = ((HSSFWorkbook) wb).getCustomPalette(); // 类HSSFPalette用于求的颜色的国际标准形式
  450. HSSFColor hc = palette.getColor(fontColor);
  451. String align = convertAlignToHtml(alignment);
  452. int columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
  453. _style +="font-weight:" + boldWeight + ";font-size: " + hf.getFontHeight() / 2 + "%;text-align:" + align + ";width:" + columnWidth + "px;";
  454. String fontColorStr = convertToStardColor(hc);
  455. if (fontColorStr != null && !"".equals(fontColorStr.trim())) {
  456. _style +="color:" + fontColorStr + ";"; // 字体颜色
  457. }
  458. short bgColor = cellStyle.getFillForegroundColor();
  459. hc = palette.getColor(bgColor);
  460. String bgColorStr = convertToStardColor(hc);
  461. if (bgColorStr != null && !"".equals(bgColorStr.trim())) {
  462. _style +="background-color:" + bgColorStr + ";"; // 背景颜色
  463. }
  464. _style +=getBorderStyle(palette, 0, cellStyle.getBorderTop().getCode(), cellStyle.getTopBorderColor());
  465. _style +=getBorderStyle(palette, 1, cellStyle.getBorderRight().getCode(), cellStyle.getRightBorderColor());
  466. _style +=getBorderStyle(palette, 3, cellStyle.getBorderLeft().getCode(), cellStyle.getLeftBorderColor());
  467. _style +=getBorderStyle(palette, 2, cellStyle.getBorderBottom().getCode(), cellStyle.getBottomBorderColor());
  468. }
  469. String calssname="";
  470. if(!stylemap.containsKey(_style)) {
  471. int count = stylemap.size();
  472. calssname = "td"+count;
  473. stylemap.put(_style, calssname);
  474. }else {
  475. calssname = stylemap.get(_style);
  476. }
  477. if(!"".equals(calssname)) {
  478. sb.append("class='"+calssname+"'");
  479. }
  480. }
  481. }
  482. /**
  483. * 单元格内容的水平对齐方式
  484. *
  485. * @param alignment
  486. * @return
  487. */
  488. private static String convertAlignToHtml(HorizontalAlignment alignment) {
  489. String align = "center";
  490. switch (alignment) {
  491. case LEFT:
  492. align = "left";
  493. break;
  494. case CENTER:
  495. align = "center";
  496. break;
  497. case RIGHT:
  498. align = "right";
  499. break;
  500. default:
  501. break;
  502. }
  503. return align;
  504. }
  505. /**
  506. * 单元格中内容的垂直排列方式
  507. *
  508. * @param verticalAlignment
  509. * @return
  510. */
  511. private static String convertVerticalAlignToHtml(VerticalAlignment verticalAlignment) {
  512. String valign = "middle";
  513. switch (verticalAlignment) {
  514. case BOTTOM:
  515. valign = "bottom";
  516. break;
  517. case CENTER:
  518. valign = "middle";
  519. break;
  520. case TOP:
  521. valign = "top";
  522. break;
  523. default:
  524. break;
  525. }
  526. return valign;
  527. }
  528. private static String convertToStardColor(HSSFColor hc) {
  529. StringBuffer sb = new StringBuffer("");
  530. if (hc != null) {
  531. if (HSSFColor.HSSFColorPredefined.AUTOMATIC.getIndex() == hc.getIndex()) {
  532. return null;
  533. }
  534. sb.append("#");
  535. for (int i = 0; i < hc.getTriplet().length; i++) {
  536. sb.append(fillWithZero(Integer.toHexString(hc.getTriplet()[i])));
  537. }
  538. }
  539. return sb.toString();
  540. }
  541. private static String fillWithZero(String str) {
  542. if (str != null && str.length() < 2) {
  543. return "0" + str;
  544. }
  545. return str;
  546. }
  547. static String[] bordesr = {
  548. "border-top:", "border-right:", "border-bottom:", "border-left:" };
  549. static String[] borderStyles = {
  550. "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ",
  551. "solid ", "solid", "solid", "solid", "solid", "solid" };
  552. private static String getBorderStyle(HSSFPalette palette, int b, short s, short t) {
  553. if (s == 0)
  554. return bordesr[b] + borderStyles[s] + "#d0d7e5 1px;";
  555. String borderColorStr = convertToStardColor(palette.getColor(t));
  556. borderColorStr = borderColorStr == null || borderColorStr.length() < 1 ? "#000000" : borderColorStr;
  557. return bordesr[b] + borderStyles[s] + borderColorStr + " 1px;";
  558. }
  559. private static String getBorderStyle(int b, short s, XSSFColor xc) {
  560. if (s == 0)
  561. return bordesr[b] + borderStyles[s] + "#d0d7e5 1px;";
  562. if (xc != null && !"".equals(xc)) {
  563. String borderColorStr = xc.getARGBHex();// t.getARGBHex();
  564. borderColorStr = borderColorStr == null || borderColorStr.length() < 1 ? "#000000"
  565. : borderColorStr.substring(2);
  566. return bordesr[b] + borderStyles[s] + borderColorStr + " 1px;";
  567. }
  568. return "";
  569. }
  570. /*
  571. * @param content 生成的excel表格标签
  572. *
  573. * @param htmlPath 生成的html文件地址
  574. */
  575. private static void writeFile(String content, String htmlPath, Map<String,String> stylemap,String name) {
  576. File file2 = new File(htmlPath);
  577. StringBuilder sb = new StringBuilder();
  578. try {
  579. file2.createNewFile();// 创建文件
  580. sb.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>"+name+"</title><style type=\"text/css\">");
  581. sb.append("ul{list-style: none;max-width: calc(100%);padding: 0px;margin: 0px;overflow-x: scroll;white-space: nowrap;} ul li{padding: 3px 5px;display: inline-block;border-right: 1px solid #768893;} ul li.cur{color: #F59C25;} table{border-collapse:collapse;display:none;width:100%;} table.block{display: block;}");
  582. for(Map.Entry<String, String> entry : stylemap.entrySet()){
  583. String mapKey = entry.getKey();
  584. String mapValue = entry.getValue();
  585. sb.append(" ."+mapValue+"{"+mapKey+"}");
  586. }
  587. sb.append("</style><script>");
  588. sb.append("function changetab(i){var block = document.getElementsByClassName(\"block\");block[0].className = block[0].className.replace(\"block\",\"\");var cur = document.getElementsByClassName(\"cur\");cur[0].className = cur[0].className.replace(\"cur\",\"\");var curli = document.getElementById(\"li_\"+i);curli.className += ' cur';var curtable = document.getElementById(\"table_\"+i);curtable.className=' block';}");
  589. sb.append("</script></head><body>");
  590. sb.append("<div>");
  591. sb.append(content);
  592. sb.append("</div>");
  593. sb.append("</body></html>");
  594. FileUtils.write(file2, sb.toString(),"UTF-8");
  595. } catch (IOException e) {
  596. e.printStackTrace();
  597. }
  598. }
  599. private static void writeFile1(String content, String htmlPath, Map<String,String> stylemap,String name) {
  600. File file2 = new File(htmlPath);
  601. StringBuilder sb = new StringBuilder();
  602. try {
  603. file2.createNewFile();// 创建文件
  604. sb.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>"+name+"</title><style type=\"text/css\">");
  605. sb.append("ul{list-style: none;max-width: calc(100%);padding: 0px;margin: 0px;overflow-x: scroll;white-space: nowrap;} ul li{padding: 3px 5px;display: inline-block;border-right: 1px solid #768893;} ul li.cur{color: #F59C25;} table{border-collapse:collapse;width:100%;} td{border: solid #000000 1px; min-width: 200px;}");
  606. sb.append("</style></head><body>");
  607. sb.append("<div>");
  608. sb.append(content);
  609. sb.append("</div>");
  610. sb.append("</body></html>");
  611. FileUtils.write(file2, sb.toString(),"UTF-8");
  612. } catch (IOException e) {
  613. e.printStackTrace();
  614. }
  615. }
  616. }

3、html样式解析

3.1 加载图片-URL链接

src设置需要加载的图片地址,alt是未加载到链接内容时展示的提示语

  1. <img src="http://www.baidu.com/images/xx.jpg" alt="暂未加载图像">
3.2 设置图片大小

可以直接按比例设置100%;也可以直接按100px等比例设置

  1. width="图片宽度" height="图片高度"
  2. width=100%
3.3 设置标题-底色&加粗

hX是标题设置;background-color设置底色;font-weight:bold是加粗

  1. <h4 style="background-color:LightSkyBlue;font-weight:bold;">标题</h4>
3.4 圆点样式

设置为带圆点样式的语句

  1. <li id='li_1' οnclick='changetab(1)'>第一张</li>
3.5 url链接显示为设置内容

不直接展示该链接,显示为“点击查看内容”可点击跳转
点击查看内容

3.6 表格 – 一行三列
  1. <table border="1">
  2. <tr>
  3. <td>100</td>
  4. <td>200</td>
  5. <td>300</td>
  6. </tr>
  7. </table>
3.6 表格 – 两行三列
  1. <table border="1">
  2. <tr>
  3. <td> 1 </td>
  4. <td> 2 </td>
  5. <td> 3 </td>
  6. </tr>
  7. <tr>
  8. <td>400</td>
  9. <td>500</td>
  10. <td>600</td>
  11. </tr>
3.7 段落

段落正文中的具体内容

  1. <p>段落段落段落段落段落段落段落</p>

4、时间工具类

专供表格使用相关的时间工具类,解决格式转换的问题。

  1. //DateUtil
  2. public class DateUtil {
  3. public static boolean isCellDateFormatted(Cell cell)
  4. {
  5. if (cell == null) {
  6. return false;
  7. }
  8. boolean bDate = false;
  9. double d = cell.getNumericCellValue();
  10. if (isValidExcelDate(d)) {
  11. CellStyle style = cell.getCellStyle();
  12. if (style == null) {
  13. return false;
  14. }
  15. int i = style.getDataFormat();
  16. String f = style.getDataFormatString();
  17. bDate = isADateFormat(i, f);
  18. }
  19. return bDate;
  20. }
  21. public static boolean isADateFormat(int formatIndex, String formatString)
  22. {
  23. if (isInternalDateFormat(formatIndex)) {
  24. return true;
  25. }
  26. if ((formatString == null) || (formatString.length() == 0)) {
  27. return false;
  28. }
  29. String fs = formatString;
  30. //添加以支持汉字格式wingzing
  31. fs = fs.replaceAll("[\"|\']","").replaceAll("[年|月|日|时|分|秒|毫秒|微秒]", "");
  32. fs = fs.replaceAll("\\\\-", "-");
  33. fs = fs.replaceAll("\\\\,", ",");
  34. fs = fs.replaceAll("\\\\.", ".");
  35. fs = fs.replaceAll("\\\\ ", " ");
  36. fs = fs.replaceAll(";@", "");
  37. fs = fs.replaceAll("^\\[\\$\\-.*?\\]", "");
  38. fs = fs.replaceAll("^\\[[a-zA-Z]+\\]", "");
  39. return (fs.matches("^[yYmMdDhHsS\\-/,. :]+[ampAMP/]*$"));
  40. }
  41. public static boolean isInternalDateFormat(int format)
  42. {
  43. switch (format) {
  44. case 14:
  45. case 15:
  46. case 16:
  47. case 17:
  48. case 18:
  49. case 19:
  50. case 20:
  51. case 21:
  52. case 22:
  53. case 45:
  54. case 46:
  55. case 47:
  56. return true;
  57. case 23:
  58. case 24:
  59. case 25:
  60. case 26:
  61. case 27:
  62. case 28:
  63. case 29:
  64. case 30:
  65. case 31:
  66. case 32:
  67. case 33:
  68. case 34:
  69. case 35:
  70. case 36:
  71. case 37:
  72. case 38:
  73. case 39:
  74. case 40:
  75. case 41:
  76. case 42:
  77. case 43:
  78. case 44: } return false;
  79. }
  80. public static boolean isValidExcelDate(double value)
  81. {
  82. return (value > -4.940656458412465E-324D);
  83. }
  84. }

参考:
https://www.runoob.com/html/html-colornames.html
https://www.cnblogs.com/mythz/p/14177739.html
https://blog.csdn.net/qq\_33697094/article/details/122736603

发表评论

表情:
评论列表 (有 0 条评论,179人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Excel文件转换Html

    背景 我的工作有时会涉及到财务数据的处理。我们大家都知道,Excel文件在处理数据中很流行并且被广泛使用。Excel让我们可以将存储在里面的数据进行数学计算。我在工作中使

    相关 poiword,excelhtml

    最近在做的项目中客户有要求,希望能够在线预览自己上传的附件,本想使用第三方插件,但是由于一些不可描述的原因,最后只能选择poi,手工实现用户的需求.本人在查了不少网上资料后,最