Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
      SpecRunner - Acceptance Test Driven Development Tool
      Copyright (C) 2011-2014  Thiago Santos
  
      This program is free software: you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published by
      the Free Software Foundation, either version 3 of the License, or
      (at your option) any later version.
  
     This program is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU General Public License for more details.
 
     You should have received a copy of the GNU General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>
  */
 package org.specrunner.source.excel;
 
 import java.io.File;
 import java.net.URI;
 import java.util.Map;
 import java.util.Set;
 
 import nu.xom.Element;
 
Loader of Excel files.

Author(s):
Thiago Santos
 
 @SuppressWarnings("serial")
 public class SourceFactoryExcel extends AbstractSourceFactory {

    
Extension of 2007 Excel files.
 
     public static final String XLSX = ".xlsx";

    
Extension of 97-2003 Excel files.
 
     public static final String XLS = ".xls";

    
Prefix to be used for specify attributes in cell comments expected to be added to the table definition.
 
     public static final String TABLE_ATTRIBUTE = "t.";

    
Prefix to be used for specify attributes in cell comments expected to be added to the caption definition.
 
     public static final String CAPTION_ATTRIBUTE = "c.";

    
Prefix to be used for specify attributes in cell comments expected to be added to the row definition.
 
     public static final String ROW_ATTRIBUTE = "r.";

    
Load a document from a target.

Parameters:
uri The target corresponding uri (if any).
target The target.
encoding The encoding.
Returns:
The document, if exists, null, otherwise.
Throws:
org.specrunner.source.SourceException On load error.
    @Override
    protected Document fromTarget(URI uriString targetString encodingthrows SourceException {
        Element html = new Element("html");
        Document result = new Document(html);
        OPCPackage pkg = null;
        InputStream in = null;
        POIFSFileSystem fsys = null;
        try {
            Workbook wb = null;
            if (isFile(uritarget)) {
                if (..isDebugEnabled()) {
                    ..debug("Source from file:" + target);
                }
                in = new FileInputStream(new File(target));
            } else {
                if (..isDebugEnabled()) {
                    ..debug("Source from URI:" + uri);
                }
                in = uri.toURL().openStream();
            }
            if (target.trim().toLowerCase().endsWith()) {
                pkg = OPCPackage.open(in);
                wb = new XSSFWorkbook(pkg);
            } else {
                fsys = new POIFSFileSystem(in);
                wb = new HSSFWorkbook(fsys);
            }
            for (int i = 0; i < wb.getNumberOfSheets(); i++) {
                Sheet sheet = wb.getSheetAt(i);
                Map<StringDimensionspanMap = new HashMap<StringDimension>();
                Set<StringignoreMap = new HashSet<String>();
                for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
                    CellRangeAddress region = sheet.getMergedRegion(j);
                    for (int x = region.getFirstRow(); x <= region.getLastRow(); x++) {
                        for (int y = region.getFirstColumn(); y <= region.getLastColumn(); y++) {
                            if (x == region.getFirstRow() && y == region.getFirstColumn()) {
                                spanMap.put(x + "," + ynew Dimension(region.getLastRow() - x + 1, region.getLastColumn() - y + 1));
                            } else {
                                ignoreMap.add(x + "," + y);
                            }
                        }
                    }
                }
                Element table = new Element("table");
                table.addAttribute(new Attribute("border""1"));
                html.appendChild(table);
                Element caption = readCaption(tablesheet);
                Iterator<Rowite = sheet.iterator();
                readBody(tablecaptionspanMapignoreMapiteheaders(tablecaptionspanMapignoreMapite));
            }
        } catch (Exception e) {
            if (..isDebugEnabled()) {
                ..debug(e.getMessage(), e);
            }
            throw new SourceException(e);
        } finally {
            if (pkg != null) {
                try {
                    pkg.close();
                } catch (IOException e) {
                    if (..isDebugEnabled()) {
                        ..debug(e.getMessage(), e);
                    }
                    throw new SourceException(e);
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    if (..isDebugEnabled()) {
                        ..debug(e.getMessage(), e);
                    }
                    throw new SourceException(e);
                }
            }
        }
        return result;
    }

    
Cell span holder.

Author(s):
Thiago Santos
    private static class Dimension {
        
Rowspan.
        private int rows;
        
Colspan.
        private int cols;

        
Default constructor.

Parameters:
rows Number of rows.
cols Number of columns.
        public Dimension(int rowsint cols) {
            this. = rows;
            this. = cols;
        }
    }

    
Get caption.

Parameters:
table The target table.
sheet The sheet.
Returns:
The caption.
    protected Element readCaption(Element tableSheet sheet) {
        Element caption = new Element("caption");
        table.appendChild(caption);
        {
            caption.appendChild(sheet.getSheetName());
        }
        return caption;
    }

    
Read header information.

Parameters:
table The target table.
caption The caption element.
spanMap Map of span cells.
ignore Set of cells to ignore.
ite The row iterator.
Returns:
The number of columns to read.
    protected int headers(Element tableElement captionMap<StringDimensionspanMapSet<StringignoreIterator<Rowite) {
        int result = 0;
        Element thead = new Element("thead");
        table.appendChild(thead);
        {
            Element tr = new Element("tr");
            thead.appendChild(tr);
            {
                if (ite.hasNext()) {
                    Row row = ite.next();
                    result = row.getLastCellNum();
                    for (int i = 0; i < resulti++) {
                        Cell cell = row.getCell(i);
                        if (cell != null) {
                            String key = cell.getRowIndex() + "," + cell.getColumnIndex();
                            if (ignore.contains(key)) {
                                continue;
                            }
                            Element th = new Element("th");
                            tr.appendChild(th);
                            th.appendChild(String.valueOf(extractVal(cell)));
                            addAttributes(tablecaptiontrthcellspanMap.get(key));
                        }
                    }
                }
            }
        }
        return result;
    }

    
Add information from cell comments.

Parameters:
table The table element.
caption The table caption.
row The row element.
item The header element.
cell The cell to read comments from.
p The pair, if exist.
    private void addAttributes(Element tableElement captionElement rowElement itemCell cellDimension p) {
        Comment c = cell.getCellComment();
        if (c != null) {
            RichTextString rts = c.getString();
            if (rts != null) {
                String text = rts.getString();
                StringTokenizer st = new StringTokenizer(text"\n");
                while (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    int pos = token.indexOf('=');
                    if (pos > 0) {
                        String name = token.substring(0, pos);
                        String value = token.substring(pos + 1).replace("\"""");
                        if (name.startsWith()) {
                            table.addAttribute(new Attribute(name.substring(.length(), name.length()), value));
                        } else if (name.startsWith()) {
                            caption.addAttribute(new Attribute(name.substring(.length(), name.length()), value));
                        } else if (name.startsWith()) {
                            row.addAttribute(new Attribute(name.substring(.length(), name.length()), value));
                        } else {
                            item.addAttribute(new Attribute(namevalue));
                        }
                    }
                }
            }
        }
        if (p != null) {
            if (p.rows > 1) {
                item.addAttribute(new Attribute("rowspan", String.valueOf(p.rows)));
            }
            if (p.cols > 1) {
                item.addAttribute(new Attribute("colspan", String.valueOf(p.cols)));
            }
        }
    }

    
Read content of a table, using the rows iterator and the number of columns.

Parameters:
table The table.
caption The table caption.
spanMap Map of span cells.
ignore Set of cells to ignore.
ite The row iterator.
columns The number of columns to read.
    protected void readBody(Element tableElement captionMap<StringDimensionspanMapSet<StringignoreIterator<Rowiteint columns) {
        Element tbody = new Element("tbody");
        table.appendChild(tbody);
        {
            while (ite.hasNext()) {
                Element tr = new Element("tr");
                tbody.appendChild(tr);
                {
                    Row row = ite.next();
                    // invalid lines return -1 in row.getFirstCellNum().
                    if (row.getFirstCellNum() < 0) {
                        continue;
                    }
                    for (int k = 0; k < columnsk++) {
                        Cell cell = row.getCell(k);
                        String key = null;
                        if (cell != null) {
                            key = cell.getRowIndex() + "," + cell.getColumnIndex();
                            if (ignore.contains(key)) {
                                continue;
                            }
                        }
                        Element td = new Element("td");
                        tr.appendChild(td);
                        td.appendChild(String.valueOf(extractVal(cell)));
                        if (cell != null) {
                            addAttributes(tablecaptiontrtdcellspanMap.get(key));
                        }
                    }
                }
            }
        }
    }

    
Extract the value of a given cell.

Parameters:
cell The cell.
Returns:
The corresponding object.
    protected Object extractVal(Cell cell) {
        if (cell == null) {
            return "";
        }
        Object val = null;
        switch (cell.getCellType()) {
        case .:
            val = null;
            break;
        case .:
            val = cell.getBooleanCellValue();
            break;
        case .:
            val = cell.getErrorCellValue();
            break;
        case .:
            val = cell.getCellFormula();
            break;
        case .:
            double d = cell.getNumericCellValue();
            String tmp = String.valueOf(d);
            if (tmp.endsWith(".0")) {
                val = tmp.substring(0, tmp.lastIndexOf('.'));
            } else {
                val = d;
            }
            break;
        case .:
            val = cell.getStringCellValue();
            break;
        default:
        }
        return val;
    }
New to GrepCode? Check out our FAQ X