Example usage for org.apache.poi.hssf.usermodel HSSFWorkbook getSheetName

List of usage examples for org.apache.poi.hssf.usermodel HSSFWorkbook getSheetName

Introduction

In this page you can find the example usage for org.apache.poi.hssf.usermodel HSSFWorkbook getSheetName.

Prototype

@Override
public String getSheetName(int sheetIndex) 

Source Link

Usage

From source file:at.spardat.xma.mdl.grid.GridPOIAdapter.java

License:Open Source License

/**
 * Transfers the spreadsheet data from the POI <code>HSSFWorkbook</code> into the <code>IGridWMServer</code>.
 * Only the sheet on the given sheetIndex is copied.
        // ww  w. j a va 2  s . com
 * @param igrid the XMA model where to copy the data
 * @param book the POI represntation of the data
 * @param sheetIndex the index of the sheet to copy
 * @return a list containing all SysExceptions describing problems with individual cell formulas or ranges
 */
public static List poi2xma(IGridWM igrid, HSSFWorkbook book, int sheetIndex) {
    GridWM grid = (GridWM) igrid;
    try {
        List errorList = new ArrayList();
        grid.setSheetName(book.getSheetName(sheetIndex));

        grid.colors.clear();
        grid.initBuildInColors();
        short ic = GridWM.HSSF_FIRST_COLOR_INDEX;
        HSSFPalette palette = book.getCustomPalette();
        for (HSSFColor color = palette.getColor(ic); ic < 64 && color != null; color = palette.getColor(++ic)) {
            grid.colors.add(ic, new GridColor(color.getTriplet()));
        }

        grid.fonts.clear();
        int numFonts = book.getNumberOfFonts();
        if (numFonts > 4) {
            // adjust for "There is no 4" see code of org.apache.poi.hssf.model.Workbook.getFontRecordAt()
            numFonts += 1;
        }
        for (short i = 0; i < numFonts; i++) {
            HSSFFont font = book.getFontAt(i);
            byte fontstyle = GridFont.FONT_NORML;
            if (font.getBoldweight() >= HSSFFont.BOLDWEIGHT_BOLD)
                fontstyle |= GridFont.FONT_BOLD;
            if (font.getItalic())
                fontstyle |= GridFont.FONT_ITALIC;
            grid.fonts.add(i, new GridFont(font.getFontName(), fontstyle, font.getColor()));
        }

        grid.styles.clear();
        for (short i = 0, numStyles = book.getNumCellStyles(); i < numStyles; i++) {
            HSSFCellStyle style = book.getCellStyleAt(i);
            grid.styles.add(i, new GridCellStyle(style.getFontIndex(), style.getFillForegroundColor()));
        }

        grid.namedRanges.clear();
        for (int i = 0, numRanges = book.getNumberOfNames(); i < numRanges; i++) {
            HSSFName name = book.getNameAt(i);
            String rangeName = name.getNameName();
            String rangeRef = null;
            try { // ranges not defined but referenced by formulas have a name but no reference in HSSF
                rangeRef = name.getReference();
            } catch (Exception exc) {
                errorList.add(new SysException(exc, ((GridWM) grid).getMessage("inconsistentRange", rangeName))
                        .setCode(GridWM.CODE_inconsistentRange));
            }
            if (rangeRef != null) {
                try {
                    GridRange range = grid.getJeksDelegate().toRange(rangeRef);
                    range.setKey(rangeName);
                    grid.namedRanges.put(rangeName, range);
                } catch (Exception exc) {
                    errorList.add(new SysException(exc,
                            ((GridWM) grid).getMessage("unsupportedReference", rangeName, rangeRef))
                                    .setCode(GridWM.CODE_unsupportedReference));
                }
            }
        }

        grid.rows.clear();
        grid.cols.clear();
        grid.cells.clear();
        grid.delegate = new GridJeksDelegate(grid);
        HSSFSheet sheet = book.getSheetAt(sheetIndex);
        int firstColNum = Integer.MAX_VALUE;
        int lastColNum = Integer.MIN_VALUE;
        for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
            HSSFRow row = sheet.getRow(i);
            if (row == null)
                continue;
            if (row.getFirstCellNum() >= 0)
                firstColNum = Math.min(firstColNum, row.getFirstCellNum());
            lastColNum = Math.max(lastColNum, row.getLastCellNum());
            if (lastColNum > 255)
                lastColNum = 255;
            for (short j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
                HSSFCell hssfcell = row.getCell(j);
                if (hssfcell == null)
                    continue;
                GridCell gridcell = grid.getOrCreateCell(i, j);
                switch (hssfcell.getCellType()) {
                case HSSFCell.CELL_TYPE_BLANK:
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    gridcell.setValue(hssfcell.getBooleanCellValue());
                    break;
                case HSSFCell.CELL_TYPE_ERROR:
                    // TODO: recherche error text
                    byte errorCode = hssfcell.getErrorCellValue();
                    //                    gridcell.setValue(errorCode);
                    gridcell.setValue("#ERROR");
                    errorList.add(new SysException(((GridWM) grid).getMessage("errorRecord",
                            grid.getJeksDelegate().toExcelRef(i, j), Byte.toString(errorCode)))
                                    .setCode(GridWM.CODE_errorRecord));
                    break;
                case HSSFCell.CELL_TYPE_FORMULA:
                    String formula = null;
                    try {
                        formula = hssfcell.getCellFormula();
                        gridcell.setFormula(formula);
                    } catch (SysException e) {
                        if (formula != null)
                            gridcell.setValue("=" + formula); //set it as text without interpretation
                        errorList.add(e);
                    }
                    break;
                case HSSFCell.CELL_TYPE_NUMERIC:
                    if (isDateCell(book, hssfcell)) {
                        gridcell.setValue(hssfcell.getDateCellValue());
                    } else {
                        gridcell.setValue(hssfcell.getNumericCellValue());
                    }
                    break;
                case HSSFCell.CELL_TYPE_STRING:
                    gridcell.setValue(hssfcell.getStringCellValue());
                    break;
                default:
                    throw new SysException("unknown cell type " + hssfcell.getCellType());
                }
                gridcell.setEditable(!hssfcell.getCellStyle().getLocked());
                gridcell.setStyle(hssfcell.getCellStyle().getIndex());
            }
        }

        final int scalefactor = 256 / 7; // empirically testet
        //        int width = sheet.getDefaultColumnWidth();  // returns nonsense
        //        width = width/scalefactor;
        //        grid.setDefaultColumnWidth(width);
        for (short i = (short) firstColNum; i <= lastColNum; i++) {
            int width = sheet.getColumnWidth(i);
            width = width / scalefactor;
            grid.getOrCreateColumn(i).setWidth(width);
        }

        if (firstColNum == Integer.MAX_VALUE)
            firstColNum = 0;
        if (lastColNum == Integer.MIN_VALUE)
            lastColNum = 0;
        grid.setMaxRange(
                new GridRange(grid, sheet.getFirstRowNum(), firstColNum, sheet.getLastRowNum(), lastColNum));
        grid.setVisibleRange(grid.getMaxRange());
        return errorList;
    } finally {
        grid.handle(grid.new GridReloadEvent());
    }
}

From source file:cdc.impl.datasource.office.ExcelDataSource.java

License:LGPL

private static DataColumnDefinition[] readDataModel(String sourceName, Map params)
        throws IOException, RJException {
    BufferedInputStream is = null;
    try {/*from w  ww .  j a  va2  s .  com*/
        is = new BufferedInputStream(new FileInputStream((String) params.get(PARAM_FILE)));
        HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
        String[] sheets;
        if (params.get(PARAM_SHEET) != null) {
            sheets = new String[] { (String) params.get(PARAM_SHEET) };
        } else {
            sheets = new String[wb.getNumberOfSheets()];
            for (int i = 0; i < sheets.length; i++) {
                sheets[i] = wb.getSheetName(i);
            }
        }
        if (sheets.length == 0) {
            throw new RJException("Excel file " + params.get(PARAM_FILE) + " does not provide any sheets.");
        }
        List cols = new ArrayList();
        HSSFSheet sheet = wb.getSheet(sheets[0]);
        if (sheet == null) {
            //System.out.println("Thorwing: " + "Sheet " + sheets[0] + " is not provided by file " + params.get(PARAM_FILE));
            throw new RJException(
                    "Sheet '" + sheets[0] + "' is not provided by file " + params.get(PARAM_FILE));
        }
        HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(sheet, wb);
        //first row should provide data model
        HSSFRow row = sheet.getRow(0);
        evaluator.setCurrentRow(row);
        for (int i = 0; i < row.getPhysicalNumberOfCells(); i++) {
            HSSFCell cell = row.getCell(i);
            cols.add(new ExcelDataColumnDefinition(decodeValue(cell, evaluator),
                    DataColumnDefinition.TYPE_STRING, sourceName, i));
        }
        for (int i = 1; i < sheets.length; i++) {
            sheet = wb.getSheet(sheets[i]);
            if (sheet == null) {
                throw new RJException("Sheet '" + params.get(PARAM_SHEET) + "' is not provided by file "
                        + params.get(PARAM_FILE));
            }
            evaluator = new HSSFFormulaEvaluator(sheet, wb);
            //first row should provide data model
            row = sheet.getRow(0);
            evaluator.setCurrentRow(row);
            List localCols = new ArrayList();
            for (i = 0; i < row.getPhysicalNumberOfCells(); i++) {
                HSSFCell cell = row.getCell(i);
                DataColumnDefinition col = new ExcelDataColumnDefinition(decodeValue(cell, evaluator),
                        DataColumnDefinition.TYPE_STRING, sourceName, i);
                localCols.add(col);
            }
            List toRemove = new ArrayList();
            for (Iterator iterator = cols.iterator(); iterator.hasNext();) {
                DataColumnDefinition object = (DataColumnDefinition) iterator.next();
                if (!localCols.contains(object)) {
                    toRemove.add(object);
                }
            }
            cols.removeAll(toRemove);
        }

        return (DataColumnDefinition[]) cols.toArray(new DataColumnDefinition[] {});
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:cdc.impl.datasource.office.SheetsIterator.java

License:LGPL

public SheetsIterator(HSSFWorkbook workbook, String[] sheetNames) {
    this.workbook = workbook;
    this.sheetNames = sheetNames;
    if (sheetNames == null) {
        this.sheetNames = new String[workbook.getNumberOfSheets()];
        for (int i = 0; i < this.sheetNames.length; i++) {
            this.sheetNames[i] = workbook.getSheetName(i);
        }/*from   w w w  .  j  a v a2s.  c  om*/
    }
}

From source file:com.b510.excel.client.HSSFReadWrite.java

License:Apache License

/**
 * Method main/*from  w  w  w.  ja v a 2s  .c o m*/
 *
 * Given 1 argument takes that as the filename, inputs it and dumps the cell
 * values/types out to sys.out.<br/>
 *
 * given 2 arguments where the second argument is the word "write" and the
 * first is the filename - writes out a sample (test) spreadsheet see
 * {@link HSSFReadWrite#testCreateSampleSheet(String)}.<br/>
 *
 * given 2 arguments where the first is an input filename and the second an
 * output filename (not write), attempts to fully read in the spreadsheet
 * and fully write it out.<br/>
 *
 * given 3 arguments where the first is an input filename and the second an
 * output filename (not write) and the third is "modify1", attempts to read
 * in the spreadsheet, deletes rows 0-24, 74-99. Changes cell at row 39, col
 * 3 to "MODIFIED CELL" then writes it out. Hence this is "modify test 1".
 * If you take the output from the write test, you'll have a valid scenario.
 */
public static void main(String[] args) {
    String[] name = new String[2];
    name[0] = "HSSFReadWrite.xlsx";
    name[1] = "write";
    if (name.length < 1) {
        System.err.println("At least one argument expected");
        return;
    }
    String fileName = name[0];
    try {
        if (name.length < 2) {

            HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);

            System.out.println("Data dump:\n");

            for (int k = 0; k < wb.getNumberOfSheets(); k++) {
                HSSFSheet sheet = wb.getSheetAt(k);
                int rows = sheet.getPhysicalNumberOfRows();
                System.out.println("Sheet " + k + " \"" + wb.getSheetName(k) + "\" has " + rows + " row(s).");
                for (int r = 0; r < rows; r++) {
                    HSSFRow row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }

                    int cells = row.getPhysicalNumberOfCells();
                    System.out.println("\nROW " + row.getRowNum() + " has " + cells + " cell(s).");
                    for (int c = 0; c < cells; c++) {
                        HSSFCell cell = row.getCell(c);
                        String value = null;

                        switch (cell.getCellType()) {

                        case HSSFCell.CELL_TYPE_FORMULA:
                            value = "FORMULA value=" + cell.getCellFormula();
                            break;

                        case HSSFCell.CELL_TYPE_NUMERIC:
                            value = "NUMERIC value=" + cell.getNumericCellValue();
                            break;

                        case HSSFCell.CELL_TYPE_STRING:
                            value = "STRING value=" + cell.getStringCellValue();
                            break;

                        default:
                        }
                        System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE=" + value);
                    }
                }
            }
        } else if (name.length == 2) {
            if (name[1].toLowerCase().equals("write")) {
                System.out.println("Write mode");
                long time = System.currentTimeMillis();
                HSSFReadWrite.testCreateSampleSheet(fileName);

                System.out.println("" + (System.currentTimeMillis() - time) + " ms generation time");
            } else {
                System.out.println("readwrite test");
                HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
                FileOutputStream stream = new FileOutputStream(name[1]);

                wb.write(stream);
                stream.close();
            }
        } else if (name.length == 3 && name[2].toLowerCase().equals("modify1")) {
            // delete row 0-24, row 74 - 99 && change cell 3 on row 39 to
            // string "MODIFIED CELL!!"

            HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
            FileOutputStream stream = new FileOutputStream(name[1]);
            HSSFSheet sheet = wb.getSheetAt(0);

            for (int k = 0; k < 25; k++) {
                HSSFRow row = sheet.getRow(k);

                sheet.removeRow(row);
            }
            for (int k = 74; k < 100; k++) {
                HSSFRow row = sheet.getRow(k);

                sheet.removeRow(row);
            }
            HSSFRow row = sheet.getRow(39);
            HSSFCell cell = row.getCell(3);
            cell.setCellValue("MODIFIED CELL!!!!!");

            wb.write(stream);
            stream.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.bayareasoftware.chartengine.ds.ExcelDataSource.java

License:Apache License

/**
 * work around bug with named cells/*from  w  w w . ja  va2  s . c om*/
 * 
 */
private static void rewriteFormulas(final HSSFWorkbook workbook) {
    //if (true) return;
    // build up a cache of names
    // this is just an easy way of fetching the HSSFName based on the string
    // representation of the name
    final Map<String, HSSFName> nameCache = new HashMap<String, HSSFName>(workbook.getNumberOfNames());
    for (int i = 0; i < workbook.getNumberOfNames(); i++) {
        final HSSFName name = workbook.getNameAt(i);
        nameCache.put(name.getNameName(), name);
    }
    // remove all the sheet names from the name references, having the sheet
    // names around messes up the formulas
    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
        nameCache.remove(workbook.getSheetName(i));
    }
    //p("Names: " + nameCache.keySet());

    // loop over all the cells and rewrite the formula ones
    for (int sheetCount = 0; sheetCount < workbook.getNumberOfSheets(); sheetCount++) {
        final HSSFSheet sheet = workbook.getSheetAt(sheetCount);
        for (final Iterator rowIterator = sheet.rowIterator(); rowIterator.hasNext();) {
            final HSSFRow row = (HSSFRow) rowIterator.next();
            for (final Iterator cellIterator = row.cellIterator(); cellIterator.hasNext();) {
                final HSSFCell cell = (HSSFCell) cellIterator.next();
                if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
                    String formula = cell.getCellFormula();
                    for (final String name : nameCache.keySet()) {
                        final Pattern pattern = Pattern.compile("(\\W|^)" + name + "(\\W|$)",
                                Pattern.CASE_INSENSITIVE);
                        final HSSFName hssfName = nameCache.get(name);
                        formula = pattern.matcher(formula)
                                .replaceAll("$1" + hssfName.getReference().replace("$", "\\$") + "$2");
                    }
                    //p("Resetting Cell (" + cell.toString()
                    //      + ") Formula:" + formula);
                    cell.setCellFormula(formula);
                } // end if
            } // end for
        } // end for
    } // end for
}

From source file:com.cladonia.xngreditor.ImportUtilities.java

License:Open Source License

public static String[] getWorkSheets(File toSplit) throws FileNotFoundException, IOException, Exception {

    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(toSplit));
    HSSFWorkbook wb = new HSSFWorkbook(fs);

    String[] workSheets = new String[wb.getNumberOfSheets() + 1];
    //this.tablesCombo.addItem("- Please Select -");
    workSheets[0] = "- Please Select -";
    for (int cnt = 0; cnt < wb.getNumberOfSheets(); ++cnt) {
        workSheets[cnt + 1] = wb.getSheetName(cnt);

    }//from   w w  w .  j av  a  2s  . c  o  m

    return (workSheets);

}

From source file:com.frameworkset.platform.cms.searchmanager.extractors.CmsExtractorMsExcel.java

License:Open Source License

/**
 * Extracts the text from the Excel table content.<p>
 * //from   www .ja  v a 2 s  .  c o  m
 * @param in the document input stream
 * @return the extracted text
 * @throws IOException if something goes wring
 */
protected String extractTableContent(InputStream in) throws IOException {

    HSSFWorkbook excelWb = new HSSFWorkbook(in);
    StringBuffer result = new StringBuffer(4096);

    int numberOfSheets = excelWb.getNumberOfSheets();

    for (int i = 0; i < numberOfSheets; i++) {
        HSSFSheet sheet = excelWb.getSheetAt(i);
        int numberOfRows = sheet.getPhysicalNumberOfRows();
        if (numberOfRows > 0) {

            if (CmsStringUtil.isNotEmpty(excelWb.getSheetName(i))) {
                // append sheet name to content
                if (i > 0) {
                    result.append("\n\n");
                }
                result.append(excelWb.getSheetName(i).trim());
                result.append(":\n\n");
            }

            Iterator rowIt = sheet.rowIterator();
            while (rowIt.hasNext()) {
                HSSFRow row = (HSSFRow) rowIt.next();
                if (row != null) {
                    boolean hasContent = false;
                    Iterator it = row.cellIterator();
                    while (it.hasNext()) {
                        HSSFCell cell = (HSSFCell) it.next();
                        String text = null;
                        try {
                            switch (cell.getCellType()) {
                            case HSSFCell.CELL_TYPE_BLANK:
                            case HSSFCell.CELL_TYPE_ERROR:
                                // ignore all blank or error cells
                                break;
                            case HSSFCell.CELL_TYPE_NUMERIC:
                                text = Double.toString(cell.getNumericCellValue());
                                break;
                            case HSSFCell.CELL_TYPE_BOOLEAN:
                                text = Boolean.toString(cell.getBooleanCellValue());
                                break;
                            case HSSFCell.CELL_TYPE_STRING:
                            default:
                                text = cell.getStringCellValue();
                                break;
                            }
                        } catch (Exception e) {
                            // ignore this cell
                        }
                        if (CmsStringUtil.isNotEmpty(text)) {
                            result.append(text.trim());
                            result.append(' ');
                            hasContent = true;
                        }
                    }
                    if (hasContent) {
                        // append a newline at the end of each row that has content                            
                        result.append('\n');
                    }
                }
            }
        }
    }

    return result.toString();
}

From source file:com.isotrol.impe3.idx.oc.extractors.ExtractorMsExcel.java

License:Open Source License

/**
 * Extracts the text from the Excel table content.<p>
 * //w w  w  .  j  av a2  s .  c  om
 * @param in the document input stream
 * @return the extracted text
 * @throws IOException if something goes wring
 * @deprecated
 */
protected String extractTableContent(InputStream in) throws IOException {

    HSSFWorkbook excelWb = new HSSFWorkbook(in);
    StringBuffer result = new StringBuffer(4096);

    int numberOfSheets = excelWb.getNumberOfSheets();

    for (int i = 0; i < numberOfSheets; i++) {
        HSSFSheet sheet = excelWb.getSheetAt(i);
        int numberOfRows = sheet.getPhysicalNumberOfRows();
        if (numberOfRows > 0) {

            if (excelWb.getSheetName(i) != null && !excelWb.getSheetName(i).trim().equals("")) {
                // append sheet name to content
                if (i > 0) {
                    result.append("\n\n");
                }
                result.append(excelWb.getSheetName(i).trim());
                result.append(":\n\n");
            }

            Iterator<?> rowIt = sheet.rowIterator();
            while (rowIt.hasNext()) {
                HSSFRow row = (HSSFRow) rowIt.next();
                if (row != null) {
                    boolean hasContent = false;
                    Iterator<?> it = row.cellIterator();
                    while (it.hasNext()) {
                        HSSFCell cell = (HSSFCell) it.next();
                        String text = null;
                        try {
                            switch (cell.getCellType()) {
                            case HSSFCell.CELL_TYPE_BLANK:
                            case HSSFCell.CELL_TYPE_ERROR:
                                // ignore all blank or error cells
                                break;
                            case HSSFCell.CELL_TYPE_NUMERIC:
                                text = Double.toString(cell.getNumericCellValue());
                                break;
                            case HSSFCell.CELL_TYPE_BOOLEAN:
                                text = Boolean.toString(cell.getBooleanCellValue());
                                break;
                            case HSSFCell.CELL_TYPE_STRING:
                            default:
                                text = cell.getStringCellValue();
                                break;
                            }
                        } catch (Exception e) {
                            // ignore this cell
                        }
                        if ((text != null) && (text.length() != 0)) {
                            result.append(text.trim());
                            result.append(' ');
                            hasContent = true;
                        }
                    }
                    if (hasContent) {
                        // append a newline at the end of each row that has content
                        result.append('\n');
                    }
                }
            }
        }
    }

    return result.toString();
}

From source file:com.krawler.esp.servlets.fileUploadXLS.java

License:Open Source License

/** 
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request/*  ww  w  . j  av a  2s  .co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    JSONObject jobj = new JSONObject();
    try {
        jobj.put("success", true);
        FileItemFactory factory = new DiskFileItemFactory(4096, new File("/tmp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(10000000);
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();
        String destinationDirectory = StorageHandler.GetDocStorePath() + "xlsfiles";
        String fileName = null;
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (fi.isFormField())
                continue;
            fileName = fi.getName();

            fi.write(new File(destinationDirectory, fileName));
        }

        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(destinationDirectory + "/" + fileName));
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        int count = wb.getNumberOfSheets();
        JSONArray jArr = new JSONArray();
        for (int x = 0; x < count; x++) {
            JSONObject obj = new JSONObject();
            obj.put("name", wb.getSheetName(x));
            obj.put("index", x);
            jArr.put(obj);
        }
        jobj.put("file", destinationDirectory + "/" + fileName);
        jobj.put("data", jArr);
        jobj.put("msg", "Image has been successfully uploaded");
        jobj.put("lsuccess", true);
        jobj.put("valid", true);
    } catch (Exception e) {
        Logger.getLogger(fileUploadXLS.class.getName()).log(Level.SEVERE, null, e);
        try {
            jobj.put("msg", e.getMessage());
            jobj.put("lsuccess", false);
            jobj.put("valid", true);
        } catch (Exception ex) {
        }
    } finally {
        out.println(jobj);
    }
}

From source file:com.krawler.spring.importFunctionality.ImportController.java

License:Open Source License

public ModelAndView fileUploadXLS(HttpServletRequest request, HttpServletResponse response) {
    String View = "jsonView-ex";
    JSONObject jobj = new JSONObject();
    try {/*ww  w .  j  av  a2s  .  co m*/
        System.out.println("A(( Upload XLS start : " + new Date());
        jobj.put("success", true);
        FileItemFactory factory = new DiskFileItemFactory(4096,
                new File(ConfigReader.getinstance().get("UploadTempDir", "/tmp")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(10485760);
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();
        String destinationDirectory = storageHandlerImpl.GetDocStorePath() + "xlsfiles";
        String fileName = null;
        String fileid = UUID.randomUUID().toString();
        fileid = fileid.replaceAll("-", ""); // To append UUID without "-" [SK]
        String Ext = "";
        while (i.hasNext()) {
            java.io.File destDir = new java.io.File(destinationDirectory);
            if (!destDir.exists()) { //Create xls file's folder if not present
                destDir.mkdirs();
            }

            FileItem fi = (FileItem) i.next();
            if (fi.isFormField())
                continue;
            fileName = fi.getName();
            if (fileName.contains(".")) {
                Ext = fileName.substring(fileName.lastIndexOf("."));
                int startIndex = fileName.contains("\\") ? (fileName.lastIndexOf("\\") + 1) : 0;
                fileName = fileName.substring(startIndex, fileName.lastIndexOf("."));
            }

            if (fileName.length() > 28) { // To fixed Mysql ERROR 1103 (42000): Incorrect table name
                throw new DataInvalidateException("Filename is too long, use upto 28 characters.");
            }
            fi.write(new File(destinationDirectory, fileName + "_" + fileid + Ext));
        }

        POIFSFileSystem fs = new POIFSFileSystem(
                new FileInputStream(destinationDirectory + "/" + fileName + "_" + fileid + Ext));
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        int count = wb.getNumberOfSheets();
        JSONArray jArr = new JSONArray();
        for (int x = 0; x < count; x++) {
            JSONObject obj = new JSONObject();
            obj.put("name", wb.getSheetName(x));
            obj.put("index", x);
            jArr.put(obj);
        }
        jobj.put("file", destinationDirectory + "/" + fileName + "_" + fileid + Ext);
        jobj.put("filename", fileName + "_" + fileid + Ext);
        jobj.put("data", jArr);
        jobj.put("msg", "Image has been successfully uploaded");
        jobj.put("lsuccess", true);
        jobj.put("valid", true);
    } catch (FileUploadBase.SizeLimitExceededException ex) {
        Logger.getLogger(ImportController.class.getName()).log(Level.SEVERE, null, ex);
        jobj.put("msg", "File exceeds max size limit i.e 10MB.");
        jobj.put("lsuccess", false);
        jobj.put("valid", true);
    } catch (Exception e) {
        Logger.getLogger(ImportController.class.getName()).log(Level.SEVERE, null, e);
        try {
            String msg = e.getMessage().contains("Invalid header signature;")
                    ? "Not a real xls file. File contents are not XLS content/corrupted content."
                    : e.getMessage();
            jobj.put("msg", msg);
            jobj.put("lsuccess", false);
            jobj.put("valid", true);
        } catch (Exception ex) {
        }
    } finally {
        System.out.println("A(( Upload XLS end : " + new Date());
        return new ModelAndView(View, "model", jobj.toString());
    }
}