Subversion Repositories SmartDukaan

Rev

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