You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ExcelToHtmlConverter.java 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.hssf.converter;
  16. import static org.apache.poi.hssf.converter.AbstractExcelUtils.appendAlign;
  17. import static org.apache.poi.hssf.converter.AbstractExcelUtils.buildMergedRangesMap;
  18. import static org.apache.poi.hssf.converter.AbstractExcelUtils.getBorderStyle;
  19. import static org.apache.poi.hssf.converter.AbstractExcelUtils.getBorderWidth;
  20. import static org.apache.poi.hssf.converter.AbstractExcelUtils.getColor;
  21. import static org.apache.poi.hssf.converter.AbstractExcelUtils.getMergedRange;
  22. import static org.apache.poi.hssf.converter.AbstractExcelUtils.isEmpty;
  23. import static org.apache.poi.hssf.converter.AbstractExcelUtils.isNotEmpty;
  24. import static org.apache.poi.hssf.converter.AbstractExcelUtils.loadXls;
  25. import java.io.File;
  26. import java.io.IOException;
  27. import java.io.InputStream;
  28. import java.util.ArrayList;
  29. import java.util.LinkedHashMap;
  30. import java.util.List;
  31. import java.util.Map;
  32. import javax.xml.parsers.ParserConfigurationException;
  33. import javax.xml.transform.OutputKeys;
  34. import javax.xml.transform.Transformer;
  35. import javax.xml.transform.dom.DOMSource;
  36. import javax.xml.transform.stream.StreamResult;
  37. import org.apache.logging.log4j.LogManager;
  38. import org.apache.logging.log4j.Logger;
  39. import org.apache.poi.hpsf.SummaryInformation;
  40. import org.apache.poi.hssf.usermodel.HSSFCell;
  41. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  42. import org.apache.poi.hssf.usermodel.HSSFFont;
  43. import org.apache.poi.hssf.usermodel.HSSFRichTextString;
  44. import org.apache.poi.hssf.usermodel.HSSFRow;
  45. import org.apache.poi.hssf.usermodel.HSSFSheet;
  46. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  47. import org.apache.poi.hssf.util.HSSFColor;
  48. import org.apache.poi.hwpf.converter.HtmlDocumentFacade;
  49. import org.apache.poi.ss.formula.eval.ErrorEval;
  50. import org.apache.poi.ss.usermodel.BorderStyle;
  51. import org.apache.poi.ss.util.CellRangeAddress;
  52. import org.apache.poi.util.Beta;
  53. import org.apache.poi.util.XMLHelper;
  54. import org.w3c.dom.Document;
  55. import org.w3c.dom.Element;
  56. import org.w3c.dom.Text;
  57. /**
  58. * Converts xls files (97-2007) to HTML file.
  59. */
  60. @Beta
  61. public class ExcelToHtmlConverter extends AbstractExcelConverter {
  62. private static final Logger LOG = LogManager.getLogger(ExcelToHtmlConverter.class);
  63. /**
  64. * Java main() interface to interact with ExcelToHtmlConverter
  65. *
  66. * <p>
  67. * Usage: ExcelToHtmlConverter infile outfile
  68. * </p>
  69. * Where infile is an input .xls file ( Word 97-2007) which will be rendered
  70. * as HTML into outfile
  71. */
  72. public static void main(String[] args) throws Exception {
  73. if (args.length < 2) {
  74. System.err.println("Usage: ExcelToHtmlConverter <inputFile.xls> <saveTo.html>");
  75. return;
  76. }
  77. System.out.println("Converting " + args[0]);
  78. System.out.println("Saving output to " + args[1]);
  79. Document doc = ExcelToHtmlConverter.process(new File(args[0]));
  80. DOMSource domSource = new DOMSource(doc);
  81. StreamResult streamResult = new StreamResult(new File(args[1]));
  82. Transformer serializer = XMLHelper.newTransformer();
  83. // TODO set encoding from a command argument
  84. serializer.setOutputProperty(OutputKeys.METHOD, "html");
  85. serializer.transform(domSource, streamResult);
  86. }
  87. /**
  88. * Converts Excel file (97-2007) into HTML file.
  89. *
  90. * @param xlsFile workbook file to process
  91. * @return DOM representation of result HTML
  92. * @throws IOException If an error occurs reading or writing files
  93. * @throws ParserConfigurationException If configuration is incorrect
  94. * @throws RuntimeException a number of runtime exceptions can be thrown, especially if there are problems with the
  95. * input format
  96. */
  97. public static Document process(File xlsFile) throws IOException, ParserConfigurationException {
  98. try (HSSFWorkbook workbook = loadXls(xlsFile)) {
  99. return ExcelToHtmlConverter.process(workbook);
  100. }
  101. }
  102. /**
  103. * Converts Excel file (97-2007) into HTML file.
  104. *
  105. * @param xlsStream workbook stream to process
  106. * @return DOM representation of result HTML
  107. * @throws IOException If an error occurs reading or writing files
  108. * @throws ParserConfigurationException If configuration is incorrect
  109. * @throws RuntimeException a number of runtime exceptions can be thrown, especially if there are problems with the
  110. * input format
  111. */
  112. public static Document process(InputStream xlsStream) throws IOException, ParserConfigurationException {
  113. try (HSSFWorkbook workbook = new HSSFWorkbook(xlsStream)) {
  114. return ExcelToHtmlConverter.process(workbook);
  115. }
  116. }
  117. /**
  118. * Converts Excel file (97-2007) into HTML file.
  119. *
  120. * @param workbook workbook instance to process
  121. * @return DOM representation of result HTML
  122. * @throws IOException If an error occurs reading or writing files
  123. * @throws ParserConfigurationException If configuration is incorrect
  124. * @throws RuntimeException a number of runtime exceptions can be thrown, especially if there are problems with the
  125. * input format
  126. */
  127. public static Document process(HSSFWorkbook workbook) throws IOException, ParserConfigurationException {
  128. ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(
  129. XMLHelper.newDocumentBuilder().newDocument());
  130. excelToHtmlConverter.processWorkbook(workbook);
  131. return excelToHtmlConverter.getDocument();
  132. }
  133. private String cssClassContainerCell;
  134. private String cssClassContainerDiv;
  135. private String cssClassPrefixCell = "c";
  136. private String cssClassPrefixDiv = "d";
  137. private String cssClassPrefixRow = "r";
  138. private String cssClassPrefixTable = "t";
  139. private final Map<Short, String> excelStyleToClass = new LinkedHashMap<>();
  140. private final HtmlDocumentFacade htmlDocumentFacade;
  141. private boolean useDivsToSpan;
  142. public ExcelToHtmlConverter(Document doc) {
  143. htmlDocumentFacade = new HtmlDocumentFacade(doc);
  144. }
  145. public ExcelToHtmlConverter(HtmlDocumentFacade htmlDocumentFacade) {
  146. this.htmlDocumentFacade = htmlDocumentFacade;
  147. }
  148. protected String buildStyle(HSSFWorkbook workbook, HSSFCellStyle cellStyle) {
  149. StringBuilder style = new StringBuilder();
  150. style.append("white-space:pre-wrap;");
  151. appendAlign(style, cellStyle.getAlignment());
  152. switch (cellStyle.getFillPattern()) {
  153. // no fill
  154. case NO_FILL:
  155. break;
  156. case SOLID_FOREGROUND:
  157. final HSSFColor foregroundColor = cellStyle.getFillForegroundColorColor();
  158. if (foregroundColor == null) {
  159. break;
  160. }
  161. String fgCol = getColor(foregroundColor);
  162. style.append("background-color:").append(fgCol).append(";");
  163. break;
  164. default:
  165. final HSSFColor backgroundColor = cellStyle.getFillBackgroundColorColor();
  166. if (backgroundColor == null) {
  167. break;
  168. }
  169. String bgCol = getColor(backgroundColor);
  170. style.append("background-color:").append(bgCol).append(";");
  171. break;
  172. }
  173. buildStyle_border(workbook, style, "top", cellStyle.getBorderTop(),
  174. cellStyle.getTopBorderColor());
  175. buildStyle_border(workbook, style, "right",
  176. cellStyle.getBorderRight(), cellStyle.getRightBorderColor());
  177. buildStyle_border(workbook, style, "bottom",
  178. cellStyle.getBorderBottom(), cellStyle.getBottomBorderColor());
  179. buildStyle_border(workbook, style, "left", cellStyle.getBorderLeft(),
  180. cellStyle.getLeftBorderColor());
  181. HSSFFont font = cellStyle.getFont(workbook);
  182. buildStyle_font(workbook, style, font);
  183. return style.toString();
  184. }
  185. private void buildStyle_border(HSSFWorkbook workbook, StringBuilder style,
  186. String type, BorderStyle xlsBorder, short borderColor) {
  187. if (xlsBorder == BorderStyle.NONE) {
  188. return;
  189. }
  190. StringBuilder borderStyle = new StringBuilder();
  191. borderStyle.append(getBorderWidth(xlsBorder));
  192. borderStyle.append(' ');
  193. borderStyle.append(getBorderStyle(xlsBorder));
  194. final HSSFColor color = workbook.getCustomPalette().getColor(borderColor);
  195. if (color != null) {
  196. borderStyle.append(' ');
  197. borderStyle.append(getColor(color));
  198. }
  199. style.append("border-").append(type).append(":").append(borderStyle).append(";");
  200. }
  201. void buildStyle_font(HSSFWorkbook workbook, StringBuilder style,
  202. HSSFFont font) {
  203. if (font.getBold()) {
  204. style.append("font-weight:bold;");
  205. }
  206. final HSSFColor fontColor = workbook.getCustomPalette().getColor(
  207. font.getColor());
  208. if (fontColor != null) {
  209. style.append("color: ").append(getColor(fontColor)).append("; ");
  210. }
  211. if (font.getFontHeightInPoints() != 0) {
  212. style.append("font-size:").append(font.getFontHeightInPoints()).append("pt;");
  213. }
  214. if (font.getItalic()) {
  215. style.append("font-style:italic;");
  216. }
  217. }
  218. public String getCssClassPrefixCell() {
  219. return cssClassPrefixCell;
  220. }
  221. public String getCssClassPrefixDiv() {
  222. return cssClassPrefixDiv;
  223. }
  224. public String getCssClassPrefixRow() {
  225. return cssClassPrefixRow;
  226. }
  227. public String getCssClassPrefixTable() {
  228. return cssClassPrefixTable;
  229. }
  230. @Override
  231. public Document getDocument() {
  232. return htmlDocumentFacade.getDocument();
  233. }
  234. protected String getStyleClassName(HSSFWorkbook workbook,
  235. HSSFCellStyle cellStyle) {
  236. final Short cellStyleKey = cellStyle.getIndex();
  237. String knownClass = excelStyleToClass.get(cellStyleKey);
  238. if (knownClass != null) {
  239. return knownClass;
  240. }
  241. String cssStyle = buildStyle(workbook, cellStyle);
  242. String cssClass = htmlDocumentFacade.getOrCreateCssClass(
  243. cssClassPrefixCell, cssStyle);
  244. excelStyleToClass.put(cellStyleKey, cssClass);
  245. return cssClass;
  246. }
  247. public boolean isUseDivsToSpan() {
  248. return useDivsToSpan;
  249. }
  250. protected boolean processCell(HSSFCell cell, Element tableCellElement,
  251. int normalWidthPx, int maxSpannedWidthPx, float normalHeightPt) {
  252. final HSSFCellStyle cellStyle = cell.getCellStyle();
  253. String value;
  254. switch (cell.getCellType()) {
  255. case STRING:
  256. // XXX: enrich
  257. value = cell.getRichStringCellValue().getString();
  258. break;
  259. case FORMULA:
  260. switch (cell.getCachedFormulaResultType()) {
  261. case STRING:
  262. HSSFRichTextString str = cell.getRichStringCellValue();
  263. if (str != null && str.length() > 0) {
  264. value = (str.toString());
  265. } else {
  266. value = AbstractExcelUtils.EMPTY;
  267. }
  268. break;
  269. case NUMERIC:
  270. double nValue = cell.getNumericCellValue();
  271. short df = cellStyle.getDataFormat();
  272. String dfs = cellStyle.getDataFormatString();
  273. value = _formatter.formatRawCellContents(nValue, df, dfs);
  274. break;
  275. case BOOLEAN:
  276. value = String.valueOf(cell.getBooleanCellValue());
  277. break;
  278. case ERROR:
  279. value = ErrorEval.getText(cell.getErrorCellValue());
  280. break;
  281. default:
  282. LOG.atWarn().log("Unexpected cell cachedFormulaResultType ({})", cell.getCachedFormulaResultType());
  283. value = AbstractExcelUtils.EMPTY;
  284. break;
  285. }
  286. break;
  287. case BLANK:
  288. value = AbstractExcelUtils.EMPTY;
  289. break;
  290. case NUMERIC:
  291. value = _formatter.formatCellValue(cell);
  292. break;
  293. case BOOLEAN:
  294. value = String.valueOf(cell.getBooleanCellValue());
  295. break;
  296. case ERROR:
  297. value = ErrorEval.getText(cell.getErrorCellValue());
  298. break;
  299. default:
  300. LOG.atWarn().log("Unexpected cell type ({})", cell.getCellType());
  301. return true;
  302. }
  303. final boolean noText = isEmpty(value);
  304. final boolean wrapInDivs = !noText && isUseDivsToSpan() && !cellStyle.getWrapText();
  305. if (cellStyle.getIndex() != 0) {
  306. @SuppressWarnings("resource")
  307. HSSFWorkbook workbook = cell.getRow().getSheet().getWorkbook();
  308. String mainCssClass = getStyleClassName(workbook, cellStyle);
  309. if (wrapInDivs) {
  310. tableCellElement.setAttribute("class", mainCssClass + " "
  311. + cssClassContainerCell);
  312. } else {
  313. tableCellElement.setAttribute("class", mainCssClass);
  314. }
  315. if (noText) {
  316. /*
  317. * if cell style is defined (like borders, etc.) but cell text
  318. * is empty, add "&nbsp;" to output, so browser won't collapse
  319. * and ignore cell
  320. */
  321. value = "\u00A0";
  322. }
  323. }
  324. if (isOutputLeadingSpacesAsNonBreaking() && value.startsWith(" ")) {
  325. StringBuilder builder = new StringBuilder();
  326. for (int c = 0; c < value.length(); c++) {
  327. if (value.charAt(c) != ' ') {
  328. break;
  329. }
  330. builder.append('\u00a0');
  331. }
  332. if (value.length() != builder.length()) {
  333. builder.append(value.substring(builder.length()));
  334. }
  335. value = builder.toString();
  336. }
  337. Text text = htmlDocumentFacade.createText(value);
  338. if (wrapInDivs) {
  339. Element outerDiv = htmlDocumentFacade.createBlock();
  340. outerDiv.setAttribute("class", this.cssClassContainerDiv);
  341. Element innerDiv = htmlDocumentFacade.createBlock();
  342. StringBuilder innerDivStyle = new StringBuilder();
  343. innerDivStyle.append("position:absolute;min-width:");
  344. innerDivStyle.append(normalWidthPx);
  345. innerDivStyle.append("px;");
  346. if (maxSpannedWidthPx != Integer.MAX_VALUE) {
  347. innerDivStyle.append("max-width:");
  348. innerDivStyle.append(maxSpannedWidthPx);
  349. innerDivStyle.append("px;");
  350. }
  351. innerDivStyle.append("overflow:hidden;max-height:");
  352. innerDivStyle.append(normalHeightPt);
  353. innerDivStyle.append("pt;white-space:nowrap;");
  354. appendAlign(innerDivStyle, cellStyle.getAlignment());
  355. htmlDocumentFacade.addStyleClass(outerDiv, cssClassPrefixDiv,
  356. innerDivStyle.toString());
  357. innerDiv.appendChild(text);
  358. outerDiv.appendChild(innerDiv);
  359. tableCellElement.appendChild(outerDiv);
  360. } else {
  361. tableCellElement.appendChild(text);
  362. }
  363. return isEmpty(value) && (cellStyle.getIndex() == 0);
  364. }
  365. protected void processColumnHeaders(HSSFSheet sheet, int maxSheetColumns,
  366. Element table) {
  367. Element tableHeader = htmlDocumentFacade.createTableHeader();
  368. table.appendChild(tableHeader);
  369. Element tr = htmlDocumentFacade.createTableRow();
  370. if (isOutputRowNumbers()) {
  371. // empty row at left-top corner
  372. tr.appendChild(htmlDocumentFacade.createTableHeaderCell());
  373. }
  374. for (int c = 0; c < maxSheetColumns; c++) {
  375. if (!isOutputHiddenColumns() && sheet.isColumnHidden(c)) {
  376. continue;
  377. }
  378. Element th = htmlDocumentFacade.createTableHeaderCell();
  379. String text = getColumnName(c);
  380. th.appendChild(htmlDocumentFacade.createText(text));
  381. tr.appendChild(th);
  382. }
  383. tableHeader.appendChild(tr);
  384. }
  385. /**
  386. * Creates COLGROUP element with width specified for all columns. (Except
  387. * first if {@link #isOutputRowNumbers()}{@code ==true})
  388. */
  389. protected void processColumnWidths(HSSFSheet sheet, int maxSheetColumns,
  390. Element table) {
  391. // draw COLS after we know max column number
  392. Element columnGroup = htmlDocumentFacade.createTableColumnGroup();
  393. if (isOutputRowNumbers()) {
  394. columnGroup.appendChild(htmlDocumentFacade.createTableColumn());
  395. }
  396. for (int c = 0; c < maxSheetColumns; c++) {
  397. if (!isOutputHiddenColumns() && sheet.isColumnHidden(c)) {
  398. continue;
  399. }
  400. Element col = htmlDocumentFacade.createTableColumn();
  401. col.setAttribute("width",
  402. String.valueOf(getColumnWidth(sheet, c)));
  403. columnGroup.appendChild(col);
  404. }
  405. table.appendChild(columnGroup);
  406. }
  407. protected void processDocumentInformation(SummaryInformation summaryInformation) {
  408. if (isNotEmpty(summaryInformation.getTitle())) {
  409. htmlDocumentFacade.setTitle(summaryInformation.getTitle());
  410. }
  411. if (isNotEmpty(summaryInformation.getAuthor())) {
  412. htmlDocumentFacade.addAuthor(summaryInformation.getAuthor());
  413. }
  414. if (isNotEmpty(summaryInformation.getKeywords())) {
  415. htmlDocumentFacade.addKeywords(summaryInformation.getKeywords());
  416. }
  417. if (isNotEmpty(summaryInformation.getComments())) {
  418. htmlDocumentFacade
  419. .addDescription(summaryInformation.getComments());
  420. }
  421. }
  422. /**
  423. * @return maximum 1-base index of column that were rendered, zero if none
  424. */
  425. protected int processRow(CellRangeAddress[][] mergedRanges, HSSFRow row,
  426. Element tableRowElement) {
  427. final HSSFSheet sheet = row.getSheet();
  428. final short maxColIx = row.getLastCellNum();
  429. if (maxColIx <= 0) {
  430. return 0;
  431. }
  432. final List<Element> emptyCells = new ArrayList<>(maxColIx);
  433. if (isOutputRowNumbers()) {
  434. Element tableRowNumberCellElement = htmlDocumentFacade
  435. .createTableHeaderCell();
  436. processRowNumber(row, tableRowNumberCellElement);
  437. emptyCells.add(tableRowNumberCellElement);
  438. }
  439. int maxRenderedColumn = 0;
  440. for (int colIx = 0; colIx < maxColIx; colIx++) {
  441. if (!isOutputHiddenColumns() && sheet.isColumnHidden(colIx)) {
  442. continue;
  443. }
  444. CellRangeAddress range = getMergedRange(mergedRanges, row.getRowNum(), colIx);
  445. if (range != null
  446. && (range.getFirstColumn() != colIx || range.getFirstRow() != row
  447. .getRowNum())) {
  448. continue;
  449. }
  450. HSSFCell cell = row.getCell(colIx);
  451. int divWidthPx = 0;
  452. if (isUseDivsToSpan()) {
  453. divWidthPx = getColumnWidth(sheet, colIx);
  454. boolean hasBreaks = false;
  455. for (int nextColumnIndex = colIx + 1; nextColumnIndex < maxColIx; nextColumnIndex++) {
  456. if (!isOutputHiddenColumns()
  457. && sheet.isColumnHidden(nextColumnIndex)) {
  458. continue;
  459. }
  460. if (row.getCell(nextColumnIndex) != null
  461. && !isTextEmpty(row.getCell(nextColumnIndex))) {
  462. hasBreaks = true;
  463. break;
  464. }
  465. divWidthPx += getColumnWidth(sheet, nextColumnIndex);
  466. }
  467. if (!hasBreaks) {
  468. divWidthPx = Integer.MAX_VALUE;
  469. }
  470. }
  471. Element tableCellElement = htmlDocumentFacade.createTableCell();
  472. if (range != null) {
  473. if (range.getFirstColumn() != range.getLastColumn()) {
  474. tableCellElement.setAttribute(
  475. "colspan",
  476. String.valueOf(range.getLastColumn()
  477. - range.getFirstColumn() + 1));
  478. }
  479. if (range.getFirstRow() != range.getLastRow()) {
  480. tableCellElement.setAttribute(
  481. "rowspan",
  482. String.valueOf(range.getLastRow()
  483. - range.getFirstRow() + 1));
  484. }
  485. }
  486. boolean emptyCell;
  487. if (cell != null) {
  488. emptyCell = processCell(cell, tableCellElement,
  489. getColumnWidth(sheet, colIx), divWidthPx,
  490. row.getHeight() / 20f);
  491. } else {
  492. emptyCell = true;
  493. }
  494. if (emptyCell) {
  495. emptyCells.add(tableCellElement);
  496. } else {
  497. for (Element emptyCellElement : emptyCells) {
  498. tableRowElement.appendChild(emptyCellElement);
  499. }
  500. emptyCells.clear();
  501. tableRowElement.appendChild(tableCellElement);
  502. maxRenderedColumn = colIx;
  503. }
  504. }
  505. return maxRenderedColumn + 1;
  506. }
  507. protected void processRowNumber(HSSFRow row,
  508. Element tableRowNumberCellElement) {
  509. tableRowNumberCellElement.setAttribute("class", "rownumber");
  510. Text text = htmlDocumentFacade.createText(getRowName(row));
  511. tableRowNumberCellElement.appendChild(text);
  512. }
  513. protected void processSheet(HSSFSheet sheet) {
  514. processSheetHeader(htmlDocumentFacade.getBody(), sheet);
  515. final int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
  516. if (physicalNumberOfRows <= 0) {
  517. return;
  518. }
  519. Element table = htmlDocumentFacade.createTable();
  520. htmlDocumentFacade.addStyleClass(table, cssClassPrefixTable,
  521. "border-collapse:collapse;border-spacing:0;");
  522. Element tableBody = htmlDocumentFacade.createTableBody();
  523. final CellRangeAddress[][] mergedRanges = buildMergedRangesMap(sheet);
  524. final List<Element> emptyRowElements = new ArrayList<>(
  525. physicalNumberOfRows);
  526. int maxSheetColumns = 1;
  527. for (int r = sheet.getFirstRowNum(); r <= sheet.getLastRowNum(); r++) {
  528. HSSFRow row = sheet.getRow(r);
  529. if (row == null) {
  530. continue;
  531. }
  532. if (!isOutputHiddenRows() && row.getZeroHeight()) {
  533. continue;
  534. }
  535. Element tableRowElement = htmlDocumentFacade.createTableRow();
  536. htmlDocumentFacade.addStyleClass(tableRowElement,
  537. cssClassPrefixRow, "height:" + (row.getHeight() / 20f)
  538. + "pt;");
  539. int maxRowColumnNumber = processRow(mergedRanges, row,
  540. tableRowElement);
  541. if (maxRowColumnNumber == 0) {
  542. emptyRowElements.add(tableRowElement);
  543. } else {
  544. if (!emptyRowElements.isEmpty()) {
  545. for (Element emptyRowElement : emptyRowElements) {
  546. tableBody.appendChild(emptyRowElement);
  547. }
  548. emptyRowElements.clear();
  549. }
  550. tableBody.appendChild(tableRowElement);
  551. }
  552. maxSheetColumns = Math.max(maxSheetColumns, maxRowColumnNumber);
  553. }
  554. processColumnWidths(sheet, maxSheetColumns, table);
  555. if (isOutputColumnHeaders()) {
  556. processColumnHeaders(sheet, maxSheetColumns, table);
  557. }
  558. table.appendChild(tableBody);
  559. htmlDocumentFacade.getBody().appendChild(table);
  560. }
  561. protected void processSheetHeader(Element htmlBody, HSSFSheet sheet) {
  562. Element h2 = htmlDocumentFacade.createHeader2();
  563. h2.appendChild(htmlDocumentFacade.createText(sheet.getSheetName()));
  564. htmlBody.appendChild(h2);
  565. }
  566. public void processWorkbook(HSSFWorkbook workbook) {
  567. final SummaryInformation summaryInformation = workbook
  568. .getSummaryInformation();
  569. if (summaryInformation != null) {
  570. processDocumentInformation(summaryInformation);
  571. }
  572. if (isUseDivsToSpan()) {
  573. // prepare CSS classes for later usage
  574. this.cssClassContainerCell = htmlDocumentFacade
  575. .getOrCreateCssClass(cssClassPrefixCell,
  576. "padding:0;margin:0;align:left;vertical-align:top;");
  577. this.cssClassContainerDiv = htmlDocumentFacade.getOrCreateCssClass(
  578. cssClassPrefixDiv, "position:relative;");
  579. }
  580. for (int s = 0; s < workbook.getNumberOfSheets(); s++) {
  581. HSSFSheet sheet = workbook.getSheetAt(s);
  582. processSheet(sheet);
  583. }
  584. htmlDocumentFacade.updateStylesheet();
  585. }
  586. public void setCssClassPrefixCell(String cssClassPrefixCell) {
  587. this.cssClassPrefixCell = cssClassPrefixCell;
  588. }
  589. public void setCssClassPrefixDiv(String cssClassPrefixDiv) {
  590. this.cssClassPrefixDiv = cssClassPrefixDiv;
  591. }
  592. public void setCssClassPrefixRow(String cssClassPrefixRow) {
  593. this.cssClassPrefixRow = cssClassPrefixRow;
  594. }
  595. public void setCssClassPrefixTable(String cssClassPrefixTable) {
  596. this.cssClassPrefixTable = cssClassPrefixTable;
  597. }
  598. /**
  599. * Allows converter to wrap content into two additional DIVs with tricky
  600. * styles, so it will wrap across empty cells (like in Excel).
  601. * <p>
  602. * <b>Warning:</b> after enabling this mode do not serialize result HTML
  603. * with INDENT=YES option, because line breaks will make additional
  604. * (unwanted) changes
  605. */
  606. public void setUseDivsToSpan(boolean useDivsToSpan) {
  607. this.useDivsToSpan = useDivsToSpan;
  608. }
  609. }