Advertisement
Guest User

hillpath

a guest
Nov 21st, 2013
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.46 KB | None | 0 0
  1. package ToHtml;
  2.  
  3. import static org.apache.poi.ss.usermodel.CellStyle.ALIGN_CENTER;
  4. import static org.apache.poi.ss.usermodel.CellStyle.ALIGN_CENTER_SELECTION;
  5. import static org.apache.poi.ss.usermodel.CellStyle.ALIGN_FILL;
  6. import static org.apache.poi.ss.usermodel.CellStyle.ALIGN_GENERAL;
  7. import static org.apache.poi.ss.usermodel.CellStyle.ALIGN_JUSTIFY;
  8. import static org.apache.poi.ss.usermodel.CellStyle.ALIGN_LEFT;
  9. import static org.apache.poi.ss.usermodel.CellStyle.ALIGN_RIGHT;
  10. import static org.apache.poi.ss.usermodel.CellStyle.BORDER_DASHED;
  11. import static org.apache.poi.ss.usermodel.CellStyle.BORDER_DASH_DOT;
  12. import static org.apache.poi.ss.usermodel.CellStyle.BORDER_DASH_DOT_DOT;
  13. import static org.apache.poi.ss.usermodel.CellStyle.BORDER_DOTTED;
  14. import static org.apache.poi.ss.usermodel.CellStyle.BORDER_DOUBLE;
  15. import static org.apache.poi.ss.usermodel.CellStyle.BORDER_HAIR;
  16. import static org.apache.poi.ss.usermodel.CellStyle.BORDER_MEDIUM;
  17. import static org.apache.poi.ss.usermodel.CellStyle.BORDER_MEDIUM_DASHED;
  18. import static org.apache.poi.ss.usermodel.CellStyle.BORDER_MEDIUM_DASH_DOT;
  19. import static org.apache.poi.ss.usermodel.CellStyle.BORDER_MEDIUM_DASH_DOT_DOT;
  20. import static org.apache.poi.ss.usermodel.CellStyle.BORDER_NONE;
  21. import static org.apache.poi.ss.usermodel.CellStyle.BORDER_SLANTED_DASH_DOT;
  22. import static org.apache.poi.ss.usermodel.CellStyle.BORDER_THICK;
  23. import static org.apache.poi.ss.usermodel.CellStyle.BORDER_THIN;
  24. import static org.apache.poi.ss.usermodel.CellStyle.VERTICAL_BOTTOM;
  25. import static org.apache.poi.ss.usermodel.CellStyle.VERTICAL_CENTER;
  26. import static org.apache.poi.ss.usermodel.CellStyle.VERTICAL_TOP;
  27.  
  28. import java.io.BufferedReader;
  29. import java.io.Closeable;
  30. import java.io.FileInputStream;
  31. import java.io.FileWriter;
  32. import java.io.IOException;
  33. import java.io.InputStream;
  34. import java.io.InputStreamReader;
  35. import java.io.PrintWriter;
  36. import java.util.ArrayList;
  37. import java.util.Formatter;
  38. import java.util.HashMap;
  39. import java.util.HashSet;
  40. import java.util.Iterator;
  41. import java.util.List;
  42. import java.util.Map;
  43. import java.util.Set;
  44.  
  45. import org.apache.poi.hssf.usermodel.HSSFCell;
  46. import org.apache.poi.hssf.usermodel.HSSFFont;
  47. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  48. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  49. import org.apache.poi.ss.examples.html.HSSFHtmlHelper;
  50. import org.apache.poi.ss.examples.html.HtmlHelper;
  51. import org.apache.poi.ss.examples.html.XSSFHtmlHelper;
  52. import org.apache.poi.ss.format.CellFormat;
  53. import org.apache.poi.ss.format.CellFormatResult;
  54. import org.apache.poi.ss.usermodel.Cell;
  55. import org.apache.poi.ss.usermodel.CellStyle;
  56. import org.apache.poi.ss.usermodel.Font;
  57. import org.apache.poi.ss.usermodel.Row;
  58. import org.apache.poi.ss.usermodel.Sheet;
  59. import org.apache.poi.ss.usermodel.Workbook;
  60. import org.apache.poi.ss.usermodel.WorkbookFactory;
  61. import org.apache.poi.ss.util.CellRangeAddress;
  62. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  63.  
  64. /**
  65.  * This example shows how to display a spreadsheet in HTML using the classes for
  66.  * spreadsheet display.
  67.  *
  68.  * @author Ken Arnold, Industrious Media LLC
  69.  */
  70. public class ToHtml {
  71.     private final Workbook wb;
  72.     private final Appendable output;
  73.     private boolean completeHTML;
  74.     private Formatter out;
  75.     private boolean gotBounds;
  76.     private int firstColumn;
  77.     private int endColumn;
  78.     private HtmlHelper helper;
  79.  
  80.     private List<String> mergedMap = new ArrayList<String>();
  81.    
  82.     private static final String DEFAULTS_CLASS = "excelDefaults";
  83.     private static final String COL_HEAD_CLASS = "colHeader";
  84.     private static final String ROW_HEAD_CLASS = "rowHeader";
  85.  
  86.     private static final Map<Short, String> ALIGN = mapFor(ALIGN_LEFT, "left",
  87.             ALIGN_CENTER, "center", ALIGN_RIGHT, "right", ALIGN_FILL, "left",
  88.             ALIGN_JUSTIFY, "left", ALIGN_CENTER_SELECTION, "center");
  89.  
  90.     private static final Map<Short, String> VERTICAL_ALIGN = mapFor(
  91.             VERTICAL_BOTTOM, "bottom", VERTICAL_CENTER, "middle", VERTICAL_TOP,
  92.             "top");
  93.  
  94.     private static final Map<Short, String> BORDER = mapFor(BORDER_DASH_DOT,
  95.             "dashed 1pt", BORDER_DASH_DOT_DOT, "dashed 1pt", BORDER_DASHED,
  96.             "dashed 1pt", BORDER_DOTTED, "dotted 1pt", BORDER_DOUBLE,
  97.             "double 3pt", BORDER_HAIR, "solid 1px", BORDER_MEDIUM, "solid 2pt",
  98.             BORDER_MEDIUM_DASH_DOT, "dashed 2pt", BORDER_MEDIUM_DASH_DOT_DOT,
  99.             "dashed 2pt", BORDER_MEDIUM_DASHED, "dashed 2pt", BORDER_NONE,
  100.             "none", BORDER_SLANTED_DASH_DOT, "dashed 2pt", BORDER_THICK,
  101.             "solid 3pt", BORDER_THIN, "dashed 1pt");
  102.  
  103.     @SuppressWarnings({"unchecked"})
  104.     private static <K, V> Map<K, V> mapFor(Object... mapping) {
  105.         Map<K, V> map = new HashMap<K, V>();
  106.         for (int i = 0; i < mapping.length; i += 2) {
  107.             map.put((K) mapping[i], (V) mapping[i + 1]);
  108.         }
  109.         return map;
  110.     }
  111.  
  112.     /**
  113.      * Creates a new converter to HTML for the given workbook.
  114.      *
  115.      * @param wb     The workbook.
  116.      * @param output Where the HTML output will be written.
  117.      *
  118.      * @return An object for converting the workbook to HTML.
  119.      */
  120.     public static ToHtml create(Workbook wb, Appendable output) {
  121.         return new ToHtml(wb, output);
  122.     }
  123.  
  124.     /**
  125.      * Creates a new converter to HTML for the given workbook.  If the path ends
  126.      * with "<tt>.xlsx</tt>" an {@link XSSFWorkbook} will be used; otherwise
  127.      * this will use an {@link HSSFWorkbook}.
  128.      *
  129.      * @param path   The file that has the workbook.
  130.      * @param output Where the HTML output will be written.
  131.      *
  132.      * @return An object for converting the workbook to HTML.
  133.      */
  134.     public static ToHtml create(String path, Appendable output)
  135.             throws IOException {
  136.         return create(new FileInputStream(path), output);
  137.     }
  138.  
  139.     /**
  140.      * Creates a new converter to HTML for the given workbook.  This attempts to
  141.      * detect whether the input is XML (so it should create an {@link
  142.      * XSSFWorkbook} or not (so it should create an {@link HSSFWorkbook}).
  143.      *
  144.      * @param in     The input stream that has the workbook.
  145.      * @param output Where the HTML output will be written.
  146.      *
  147.      * @return An object for converting the workbook to HTML.
  148.      */
  149.     public static ToHtml create(InputStream in, Appendable output)
  150.             throws IOException {
  151.         try {
  152.             Workbook wb = WorkbookFactory.create(in);
  153.             return create(wb, output);
  154.         } catch (InvalidFormatException e){
  155.             throw new IllegalArgumentException("Cannot create workbook from stream", e);
  156.         }
  157.     }
  158.  
  159.     private ToHtml(Workbook wb, Appendable output) {
  160.         if (wb == null)
  161.             throw new NullPointerException("wb");
  162.         if (output == null)
  163.             throw new NullPointerException("output");
  164.         this.wb = wb;
  165.         this.output = output;
  166.         setupColorMap();
  167.     }
  168.  
  169.     private void setupColorMap() {
  170.         if (wb instanceof HSSFWorkbook)
  171.             helper = new HSSFHtmlHelper((HSSFWorkbook) wb);
  172.         else if (wb instanceof XSSFWorkbook)
  173.             helper = new XSSFHtmlHelper((XSSFWorkbook) wb);
  174.         else
  175.             throw new IllegalArgumentException(
  176.                     "unknown workbook type: " + wb.getClass().getSimpleName());
  177.     }
  178.  
  179.     /**
  180.      * Run this class as a program
  181.      *
  182.      * @param args The command line arguments.
  183.      *
  184.      * @throws Exception Exception we don't recover from.
  185.      */
  186.     public static void main(String[] args) throws Exception {
  187.         if(args.length < 2){
  188.             System.err.println("usage: ToHtml inputWorkbook outputHtmlFile");
  189.             return;
  190.         }
  191.  
  192.         ToHtml toHtml = create(args[0], new PrintWriter(new FileWriter(args[1])));
  193.         toHtml.setCompleteHTML(true);
  194.         toHtml.printPage();
  195.     }
  196.  
  197.     public void setCompleteHTML(boolean completeHTML) {
  198.         this.completeHTML = completeHTML;
  199.     }
  200.  
  201.     public void printPage() throws IOException {
  202.         try {
  203.             ensureOut();
  204.             if (completeHTML) {
  205.                 out.format(
  206.                         "<?xml version=\"1.0\" encoding=\"euc-kr\" ?>%n");
  207.                 out.format("<html>%n");
  208.                 out.format("<head>%n");
  209.                 out.format("</head>%n");
  210.                 out.format("<body>%n");
  211.             }
  212.  
  213.             print();
  214.  
  215.             if (completeHTML) {
  216.                 out.format("</body>%n");
  217.                 out.format("</html>%n");
  218.             }
  219.         } finally {
  220.             if (out != null)
  221.                 out.close();
  222.             if (output instanceof Closeable) {
  223.                 Closeable closeable = (Closeable) output;
  224.                 closeable.close();
  225.             }
  226.         }
  227.     }
  228.  
  229.     public void print() {
  230.         printInlineStyle();
  231.         printSheets();
  232.     }
  233.  
  234.     private void printInlineStyle() {
  235.         //out.format("<link href=\"excelStyle.css\" rel=\"stylesheet\" type=\"text/css\">%n");
  236.         out.format("<style type=\"text/css\">%n");
  237.         printStyles();
  238.         out.format("</style>%n");
  239.     }
  240.  
  241.     private void ensureOut() {
  242.         if (out == null)
  243.             out = new Formatter(output);
  244.     }
  245.  
  246.     public void printStyles() {
  247.         ensureOut();
  248.  
  249.         // First, copy the base css
  250.         BufferedReader in = null;
  251.         try {
  252.             in = new BufferedReader(new InputStreamReader(
  253.                     getClass().getResourceAsStream("excelStyle.css")));
  254.             String line;
  255.             while ((line = in.readLine()) != null) {
  256.                 out.format("%s%n", line);
  257.             }
  258.         } catch (IOException e) {
  259.             throw new IllegalStateException("Reading standard css", e);
  260.         } finally {
  261.             if (in != null) {
  262.                 try {
  263.                     in.close();
  264.                 } catch (IOException e) {
  265.                     //noinspection ThrowFromFinallyBlock
  266.                     throw new IllegalStateException("Reading standard css", e);
  267.                 }
  268.             }
  269.         }
  270.  
  271.         // now add css for each used style
  272.         Set<CellStyle> seen = new HashSet<CellStyle>();
  273.         for (int i = 0; i < wb.getNumberOfSheets(); i++) {
  274.             Sheet sheet = wb.getSheetAt(i);
  275.             Iterator<Row> rows = sheet.rowIterator();
  276.             while (rows.hasNext()) {
  277.                 Row row = rows.next();
  278.                 for (Cell cell : row) {
  279.                     CellStyle style = cell.getCellStyle();
  280.                     if (!seen.contains(style)) {
  281.                         printStyle(style);
  282.                         seen.add(style);
  283.                     }
  284.                 }
  285.             }
  286.         }
  287.     }
  288.  
  289.     private void printStyle(CellStyle style) {
  290.         out.format(".%s .%s {%n", DEFAULTS_CLASS, styleName(style));
  291.         styleContents(style);
  292.         out.format("}%n");
  293.     }
  294.  
  295.     private void styleContents(CellStyle style) {
  296.         styleOut("text-align", style.getAlignment(), ALIGN);
  297.         styleOut("vertical-align", style.getAlignment(), VERTICAL_ALIGN);
  298.         fontStyle(style);
  299.         borderStyles(style);
  300.         helper.colorStyles(style, out);
  301.     }
  302.  
  303.     private void borderStyles(CellStyle style) {
  304.         styleOut("border-left", style.getBorderLeft(), BORDER);
  305.         styleOut("border-right", style.getBorderRight(), BORDER);
  306.         styleOut("border-top", style.getBorderTop(), BORDER);
  307.         styleOut("border-bottom", style.getBorderBottom(), BORDER);
  308.     }
  309.  
  310.     private void fontStyle(CellStyle style) {
  311.         Font font = wb.getFontAt(style.getFontIndex());
  312.  
  313.         if (font.getBoldweight() >= HSSFFont.BOLDWEIGHT_NORMAL)
  314.             out.format("  font-weight: bold;%n");
  315.         if (font.getItalic())
  316.             out.format("  font-style: italic;%n");
  317.  
  318.         int fontheight = font.getFontHeightInPoints();
  319.         if (fontheight == 9) {
  320.             //fix for stupid ol Windows
  321.             fontheight = 10;
  322.         }
  323.         out.format("  font-size: %dpt;%n", fontheight);
  324.  
  325.         // Font color is handled with the other colors
  326.     }
  327.  
  328.     private String styleName(CellStyle style) {
  329.         if (style == null)
  330.             style = wb.getCellStyleAt((short) 0);
  331.         StringBuilder sb = new StringBuilder();
  332.         Formatter fmt = new Formatter(sb);
  333.         fmt.format("style_%02x", style.getIndex());
  334.         return fmt.toString();
  335.     }
  336.  
  337.     private <K> void styleOut(String attr, K key, Map<K, String> mapping) {
  338.         String value = mapping.get(key);
  339.         if (value != null) {
  340.             out.format("  %s: %s;%n", attr, value);
  341.         }
  342.     }
  343.  
  344.     private static int ultimateCellType(Cell c) {
  345.         int type = c.getCellType();
  346.         if (type == Cell.CELL_TYPE_FORMULA)
  347.             type = c.getCachedFormulaResultType();
  348.         return type;
  349.     }
  350.  
  351.     private void printSheets() {
  352.         ensureOut();
  353.         Sheet sheet = wb.getSheetAt(0);
  354.         printSheet(sheet);
  355.     }
  356.  
  357.     public void printSheet(Sheet sheet) {
  358.         ensureOut();
  359.         out.format("<table class=%s>%n", DEFAULTS_CLASS);
  360.         printCols(sheet);
  361.         printSheetContent(sheet);
  362.         out.format("</table>%n");
  363.     }
  364.  
  365.     private void printCols(Sheet sheet) {
  366.         out.format("<col/>%n");
  367.         ensureColumnBounds(sheet);
  368.         for (int i = firstColumn; i < endColumn; i++) {
  369.             out.format("<col/>%n");
  370.         }
  371.     }
  372.  
  373.     private void ensureColumnBounds(Sheet sheet) {
  374.         if (gotBounds)
  375.             return;
  376.  
  377.         Iterator<Row> iter = sheet.rowIterator();
  378.         firstColumn = (iter.hasNext() ? Integer.MAX_VALUE : 0);
  379.         endColumn = 0;
  380.         while (iter.hasNext()) {
  381.             Row row = iter.next();
  382.             short firstCell = row.getFirstCellNum();
  383.             if (firstCell >= 0) {
  384.                 firstColumn = Math.min(firstColumn, firstCell);
  385.                 endColumn = Math.max(endColumn, row.getLastCellNum());
  386.             }
  387.         }
  388.         gotBounds = true;
  389.     }
  390.  
  391.     private void printColumnHeads() {
  392.         out.format("<thead>%n");
  393.         out.format("  <tr class=%s>%n", COL_HEAD_CLASS);
  394.         out.format("    <th class=%s>&#x25CA;</th>%n", COL_HEAD_CLASS);
  395.         //noinspection UnusedDeclaration
  396.         StringBuilder colName = new StringBuilder();
  397.         for (int i = firstColumn; i < endColumn; i++) {
  398.             colName.setLength(0);
  399.             int cnum = i;
  400.             do {
  401.                 colName.insert(0, (char) ('A' + cnum % 26));
  402.                 cnum /= 26;
  403.             } while (cnum > 0);
  404.             out.format("    <th class=%s>%s</th>%n", COL_HEAD_CLASS, colName);
  405.         }
  406.         out.format("  </tr>%n");
  407.         out.format("</thead>%n");
  408.     }
  409.  
  410.     private void printSheetContent(Sheet sheet) {
  411.         //printColumnHeads();
  412.         int mergeCount = sheet.getNumMergedRegions();
  413.        
  414.         out.format("<tbody>%n");
  415.         Iterator<Row> rows = sheet.rowIterator();
  416.         while (rows.hasNext()) {
  417.             Row row = rows.next();
  418.             out.format("  <tr>%n");
  419.             //out.format("    <td class=%s>%d</td>%n", ROW_HEAD_CLASS, row.getRowNum() + 1);
  420.             for (int i = firstColumn; i < endColumn; i++) {
  421.                 String content = "&nbsp;";
  422.                 String attrs = "";
  423.                 String colAttr = "";
  424.                 String rowAttr = "";
  425.                 int mergeCol = 0;
  426.                 int mergeRow = 0;
  427.                 boolean  isWillRemoveCell= false;
  428.                 CellStyle style = null;
  429.                 if (i >= row.getFirstCellNum() && i < row.getLastCellNum()) {
  430.                     Cell cell = row.getCell(i);
  431.                    
  432.                     if (cell != null) {
  433.                        
  434.                         for (int j=0;j<mergeCount ;j++){
  435.                             CellRangeAddress address = sheet.getMergedRegion(j);
  436.                             mergeCol = address.getLastColumn() - address.getFirstColumn();
  437.                             mergeRow = address.getLastRow() - address.getFirstRow();
  438.                            
  439.                             boolean testcase = address.isInRange(cell.getRowIndex(), cell.getColumnIndex());
  440.                             if( testcase == true){
  441.                                 if ( !mergedMap.contains(address.formatAsString())){
  442.                                     mergedMap.add(address.formatAsString());
  443.                                     System.out.println(address.formatAsString()+" / "+cell.getStringCellValue()+ " / "+mergeCol+","+mergeRow);
  444.                                     colAttr = mergeCol >0 ? ("colspan="+(mergeCol+1)) : "";
  445.                                     rowAttr = mergeRow >0 ? ("rowspan="+(mergeRow+1)) : "";
  446.                                 }else{
  447.                                     isWillRemoveCell= true;
  448.                                 }
  449.                             }
  450.                         }
  451.                            
  452.                        
  453.                         style = cell.getCellStyle();
  454.                         attrs = tagStyle(cell, style);
  455.                         //Set the value that is rendered for the cell
  456.                         //also applies the format
  457.                         CellFormat cf = CellFormat.getInstance(
  458.                                 style.getDataFormatString());
  459.                         CellFormatResult result = cf.apply(cell);
  460.                         content = result.text;
  461.                         if (content.equals(""))
  462.                             content = "&nbsp;";
  463.                     }
  464.                 }
  465.                 if(isWillRemoveCell!= true){
  466.                     out.format("    <td class=%s %s %s %s>%s</td>%n", styleName(style),
  467.                             attrs, colAttr, rowAttr,   content);
  468.                    
  469.                 }
  470.                 colAttr = "";
  471.                 rowAttr = "";
  472.                 mergeCol = 0;
  473.                 mergeRow = 0;
  474.                 isWillRemoveCell= false;
  475.             }
  476.             out.format("  </tr>%n");
  477.         }
  478.         out.format("</tbody>%n");
  479.     }
  480.  
  481.     private String tagStyle(Cell cell, CellStyle style) {
  482.         if (style.getAlignment() == ALIGN_GENERAL) {
  483.             switch (ultimateCellType(cell)) {
  484.             case HSSFCell.CELL_TYPE_STRING:
  485.                 return "style=\"text-align: left;\"";
  486.             case HSSFCell.CELL_TYPE_BOOLEAN:
  487.             case HSSFCell.CELL_TYPE_ERROR:
  488.                 return "style=\"text-align: center;\"";
  489.             case HSSFCell.CELL_TYPE_NUMERIC:
  490.             default:
  491.                 // "right" is the default
  492.                 break;
  493.             }
  494.         }
  495.         return "";
  496.     }
  497. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement