Subversion Repositories SmartDukaan

Rev

Rev 8677 | Details | Compare with Previous | Last modification | View Log | RSS feed

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