Example usage for org.apache.poi.hssf.usermodel HSSFSheet getFirstRowNum

List of usage examples for org.apache.poi.hssf.usermodel HSSFSheet getFirstRowNum

Introduction

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

Prototype

@Override
public int getFirstRowNum() 

Source Link

Document

Gets the first row on the sheet

Usage

From source file:AdminServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    adminame = request.getParameter("adminname");
    adpassword = request.getParameter("adminpassword");
    request.setAttribute("adname", adminame);

    try {//  ww w.  j a v a2  s.  c  o  m
        FileInputStream file = new FileInputStream(new File("C:\\Users\\mc13082\\Desktop\\form\\new.xls"));
        HSSFWorkbook workbook = new HSSFWorkbook(file);
        HSSFSheet worksheet = workbook.getSheetAt(0);
        ArrayList Rows = new ArrayList();

        for (int j = worksheet.getFirstRowNum() + 1; j <= worksheet.getLastRowNum(); j++) {
            ArrayList row = new ArrayList();
            HSSFRow row1 = worksheet.getRow(j);

            HSSFCell cellA1 = row1.getCell(0);
            String a1Val = cellA1.getStringCellValue();
            row.add(a1Val);
            HSSFCell cellB1 = row1.getCell(1);
            String b1Val = cellB1.getStringCellValue();
            row.add(b1Val);
            HSSFCell cellC1 = row1.getCell(2);
            String c1Val = cellC1.getStringCellValue();
            row.add(c1Val);
            HSSFCell cellD1 = row1.getCell(3);
            String d1Val = cellD1.getStringCellValue();
            row.add(d1Val);
            HSSFCell cellE1 = row1.getCell(4);
            String e1Val = cellE1.getStringCellValue();
            row.add(e1Val);
            HSSFCell cellF1 = row1.getCell(5);
            String f1Val = cellF1.getStringCellValue();
            row.add(f1Val);
            HSSFCell cellG1 = row1.getCell(6);
            String g1Val = cellG1.getStringCellValue();
            row.add(g1Val);

            HSSFCell cellH1 = row1.getCell(7);
            String h1Val = cellH1.getStringCellValue();
            row.add(h1Val);

            HSSFCell cellI1 = row1.getCell(8);
            String i1Val = cellI1.getStringCellValue();
            row.add(i1Val);
            Rows.add(row);

        }

        request.setAttribute("results", Rows);
        if (adminame.equals("Admin") && adpassword.equals("admin")) {
            RequestDispatcher rd = request.getRequestDispatcher("adminHome.jsp");
            rd.forward(request, response);
        } else {
            out.println("login failed");
            RequestDispatcher rd = request.getRequestDispatcher("afailed.jsp");
            rd.include(request, response);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

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.
        //from  w  w  w .j av a 2  s .c o m
 * @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:br.solutio.licita.controlador.ControladorPregao.java

public void editandoXlsParaExportar(Object document) {
    HSSFWorkbook wb = (HSSFWorkbook) document;
    HSSFSheet planilha = wb.getSheetAt(0);

    //Move as celulas selecionadas para baixo de acordo com o valor informado
    planilha.shiftRows(planilha.getFirstRowNum(), planilha.getLastRowNum(), 5);

    HSSFRow linha0 = planilha.createRow(0);
    linha0.createCell(0).setCellValue("Instituio Licitadora:");
    planilha.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));
    linha0.createCell(2)//from  w  ww  .  ja  v  a  2  s  . c  o  m
            .setCellValue(" " + getEntidade().getInstituicaoLicitadora().getPessoaJuridica().getNomeFantasia());
    planilha.addMergedRegion(new CellRangeAddress(0, 0, 2, 6));

    HSSFRow linha1 = planilha.createRow(1);
    linha1.createCell(0).setCellValue("Numero do Pregao:");
    planilha.addMergedRegion(new CellRangeAddress(1, 1, 0, 1));
    linha1.createCell(2).setCellValue(" " + getEntidade().getNumeroPregao());
    planilha.addMergedRegion(new CellRangeAddress(1, 1, 2, 6));

    HSSFRow linha2 = planilha.createRow(2);
    linha2.createCell(0).setCellValue("Numero do Processo:");
    planilha.addMergedRegion(new CellRangeAddress(2, 2, 0, 1));
    linha2.createCell(2).setCellValue(" " + getEntidade().getNumeroProcesso());
    planilha.addMergedRegion(new CellRangeAddress(2, 2, 2, 6));

    HSSFRow linha3 = planilha.createRow(3);
    linha3.createCell(0).setCellValue("Empresa Licitante:");
    planilha.addMergedRegion(new CellRangeAddress(3, 3, 0, 1));
    linha3.createCell(2).setCellValue("Preencha com o nome de sua Empresa");
    planilha.addMergedRegion(new CellRangeAddress(3, 3, 2, 6));

    HSSFRow linha4 = planilha.createRow(4);

    //Nova coluna para a empresas adicionarem seus valores
    HSSFRow linha5 = planilha.getRow(5);
    HSSFCell celula5 = linha5.createCell(5);
    celula5.setCellValue("Valor do Licitante");

    //for para ajustar automaticamente o tamnho das colunas
    for (int i = 0; i < 6; i++) {
        planilha.autoSizeColumn(i);
    }

    //Cor da linha de titulos da tabela
    HSSFCellStyle cellStyle = wb.createCellStyle();
    cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    for (int i = 0; i < linha5.getPhysicalNumberOfCells(); i++) {
        HSSFCell cell = linha5.getCell(i);

        cell.setCellStyle(cellStyle);
    }

    CellStyle unlockedCellStyle = wb.createCellStyle();
    unlockedCellStyle.setLocked(false);

    HSSFCell celula2 = linha3.getCell(2);
    celula2.setCellStyle(unlockedCellStyle);

}

From source file:br.ufpa.psi.comportamente.labgame.mbeans.RelatoriosMB.java

License:Open Source License

public StreamedContent geraRelatorioJogadasExperimento()
        throws ParsePropertyException, IOException, InvalidFormatException {
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("Relatrio das Jogadas");

    sheet.setColumnWidth(sheet.getFirstRowNum(), (14 * 256) + 200);
    sheet.setColumnWidth(1, (14 * 256) + 200);
    sheet.setColumnWidth(4, (17 * 256) + 200);
    sheet.setColumnWidth(5, (16 * 256) + 200);

    HSSFCellStyle cs1 = workbook.createCellStyle();
    cs1.setDataFormat(HSSFDataFormat.getBuiltinFormat("d-mmm-yy"));

    HSSFCellStyle cs2 = workbook.createCellStyle();
    cs2.setDataFormat(HSSFDataFormat.getBuiltinFormat("h:mm:ss"));

    JogadaDAO jogadaDAO = new JogadaDAO();
    jogadaDAO.beginTransaction();//from w w  w  .  j ava  2s .  c  o  m
    List<Jogada> jogadas = jogadaDAO.encontrarPorExperimento(experimentoSelecionado.getId());

    int countRow = 0;
    Row row1 = sheet.createRow(countRow++);
    Cell cell = row1.createCell(0);
    cell.setCellValue("Experimento: " + experimentoSelecionado.getNome());

    Row row = sheet.createRow(countRow++);

    row.createCell(0).setCellValue("Data da Jogada");
    row.createCell(1).setCellValue("Hora da Jogada");
    row.createCell(2).setCellValue("Coluna");
    row.createCell(3).setCellValue("Linha");
    row.createCell(4).setCellValue("Pontuacao Individual");
    row.createCell(5).setCellValue("Pontuacao Coletiva");
    row.createCell(6).setCellValue("Participante");
    row.createCell(7).setCellValue("Condio");

    for (Jogada jogada : jogadas) {

        Row nrow = sheet.createRow(countRow++);

        //Data
        Cell ncell0 = nrow.createCell(0);
        ncell0.setCellValue(jogada.getMomento());
        ncell0.setCellStyle(cs1);

        //Hora
        Cell ncell1 = nrow.createCell(1);
        ncell1.setCellValue(jogada.getMomento());
        ncell1.setCellStyle(cs2);

        //Coluna
        Cell ncell2 = nrow.createCell(2);
        ncell2.setCellValue(jogada.getColunaSelecionada());

        //Linha
        Cell ncell3 = nrow.createCell(3);
        ncell3.setCellValue(jogada.getLinhaSelecionada());

        //Pontuao Individual
        Cell ncell4 = nrow.createCell(4);
        ncell4.setCellValue(jogada.getPontuacaoIndividual());

        //Pontuao Coletiva
        Cell ncell5 = nrow.createCell(5);
        ncell5.setCellValue(jogada.getPontuacaoCultural());

        //Jogador
        Cell ncell6 = nrow.createCell(6);
        ncell6.setCellValue(jogada.getJogador().getNome());

        //Id da Condio
        Cell ncell7 = nrow.createCell(7);
        ncell7.setCellValue(jogada.getIdCondicao());

    }

    jogadaDAO.stopOperation(false);

    byte[] bytes;
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        workbook.write(out);
        bytes = out.toByteArray();
    }

    InputStream ioStream = new ByteArrayInputStream(bytes);
    file = new DefaultStreamedContent(ioStream, "application/vnd.ms-excel", "Relatrio_Jogadas.xls");
    return file;
}

From source file:com.allinfinance.bo.impl.risk.T40201BOTarget.java

License:Open Source License

public String importFile(List<File> fileList, List<String> fileNameList, Operator operator) throws Exception {
    HSSFWorkbook workbook = null;/* w  w w.  j  a v a2 s  .c  om*/
    HSSFSheet sheet = null;
    HSSFRow row = null;
    // ?
    String returnMsg = "";
    // ??
    int fileNameIndex = 0;
    // ??
    String fileName = null;

    // ??
    String saCardNo = null;
    // ??
    String saLimitAmt = null;
    // ?
    String saAction = null;
    // 
    String saBrhId = operator.getOprBrhId();
    // ?
    String saOprId = operator.getOprId();
    // 
    String saInitTime = CommonFunction.getCurrentDateTime();

    TblCtlCardInf tblCtlCardInf = null;

    FileInputStream fileInputStream = null;

    for (File file : fileList) {

        fileInputStream = new FileInputStream(file);

        workbook = new HSSFWorkbook(fileInputStream);

        sheet = workbook.getSheetAt(0);

        fileName = fileNameList.get(fileNameIndex);

        for (int rowIndex = sheet.getFirstRowNum(); rowIndex <= sheet.getLastRowNum(); rowIndex++) {

            row = sheet.getRow(rowIndex);

            for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++)
                if (row.getCell(i).getCellType() != HSSFCell.CELL_TYPE_STRING)
                    returnMsg += "[ " + fileName + " ]" + (row.getRowNum() + 1) + "" + ""
                            + (i + 1) + "???<br>";

            if (!"".equals(returnMsg))
                return returnMsg;

            saCardNo = row.getCell(0).getStringCellValue();
            // ??
            if (saCardNo.getBytes().length > 19)
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "???<br>";

            saLimitAmt = row.getCell(1).getStringCellValue();
            //            saLimitAmt = CommonFunction.transYuanToFen(saLimitAmt);

            // ??
            if (!CommonFunction.isAllDigit(saLimitAmt))
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "????<br>";

            if (saLimitAmt.getBytes().length > 12)
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "???<br>";

            saAction = row.getCell(2).getStringCellValue();
            // ?
            if (!("1".equals(saAction) || "2".equals(saAction) || "3".equals(saAction) || "4".equals(saAction)))
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "???<br>";

            // ???????
            tblCtlCardInf = new TblCtlCardInf();
            tblCtlCardInf.setId(saCardNo);
            tblCtlCardInf.setSaLimitAmt(saLimitAmt);
            tblCtlCardInf.setSaAction(saAction);
            tblCtlCardInf.setSaInitZoneNo(saBrhId);
            tblCtlCardInf.setSaInitOprId(saOprId);
            tblCtlCardInf.setSaInitTime(saInitTime);
            tblCtlCardInfDAO.saveOrUpdate(tblCtlCardInf);
        }
        fileInputStream.close();
        fileNameIndex++;
    }
    return Constants.SUCCESS_CODE;
}

From source file:com.allinfinance.bo.impl.risk.T40202BOTarget.java

License:Open Source License

@SuppressWarnings("unchecked")
public String importFile(List<File> fileList, List<String> fileNameList, Operator operator) throws Exception {
    HSSFWorkbook workbook = null;/* ww w . j a v  a 2 s . c o m*/
    HSSFSheet sheet = null;
    HSSFRow row = null;
    // ?
    String returnMsg = "";
    // ??
    int fileNameIndex = 0;
    // ??
    String fileName = null;
    String sql = null;
    // 
    List<Object[]> dataList = null;

    // ??
    String saMerNo = null;
    // ??
    String saMerChName = null;
    // ??
    String saMerEnName = null;
    // ?
    String saZoneNo = null;
    // ??
    String saLimitAmt = null;
    // ?
    String saAction = null;
    // 
    String saBrhId = operator.getOprBrhId();
    // ?
    String saOprId = operator.getOprId();
    // 
    String saInitTime = CommonFunction.getCurrentDateTime();

    TblCtlMchtInf tblCtlMchtInf = null;

    FileInputStream fileInputStream = null;

    for (File file : fileList) {

        fileInputStream = new FileInputStream(file);

        workbook = new HSSFWorkbook(fileInputStream);

        sheet = workbook.getSheetAt(0);

        fileName = fileNameList.get(fileNameIndex);

        for (int rowIndex = sheet.getFirstRowNum(); rowIndex <= sheet.getLastRowNum(); rowIndex++) {

            row = sheet.getRow(rowIndex);

            for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++)
                if (row.getCell(i).getCellType() != HSSFCell.CELL_TYPE_STRING)
                    returnMsg += "[ " + fileName + " ]" + (row.getRowNum() + 1) + "" + ""
                            + (i + 1) + "???<br>";

            if (!"".equals(returnMsg))
                return returnMsg;

            saMerNo = row.getCell(0).getStringCellValue();
            // ?
            if (saMerNo.getBytes().length > 15)
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "???<br>";
            sql = "select  mcht_nm,eng_name,bank_no from TBL_MCHT_BASE_INF where MCHT_NO = '" + saMerNo + "'";

            dataList = CommonFunction.getCommQueryDAO().findBySQLQuery(sql);
            if (dataList.size() == 0)
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "??<br>";
            // ??
            saMerChName = dataList.get(0)[0].toString();
            // ??
            saMerEnName = dataList.get(0)[1].toString();
            saZoneNo = dataList.get(0)[2].toString();

            saLimitAmt = row.getCell(1).getStringCellValue();
            //            saLimitAmt = CommonFunction.transYuanToFen(saLimitAmt);

            // ??
            if (!CommonFunction.isAllDigit(saLimitAmt))
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "????<br>";

            if (saLimitAmt.getBytes().length > 12)
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "???<br>";

            saAction = row.getCell(2).getStringCellValue();
            // ?
            if (!("1".equals(saAction) || "2".equals(saAction) || "3".equals(saAction) || "4".equals(saAction)))
                return "[ " + fileName + " ]" + (row.getRowNum() + 1)
                        + "???<br>";

            // ??????
            tblCtlMchtInf = new TblCtlMchtInf();
            tblCtlMchtInf.setId(saMerNo);
            tblCtlMchtInf.setSaMerChName(saMerChName);
            tblCtlMchtInf.setSaMerEnName(saMerEnName);
            tblCtlMchtInf.setSaZoneNo(saZoneNo);
            tblCtlMchtInf.setSaLimitAmt(saLimitAmt);
            tblCtlMchtInf.setSaAction(saAction);
            tblCtlMchtInf.setSaInitZoneNo(saBrhId);
            tblCtlMchtInf.setSaInitOprId(saOprId);
            tblCtlMchtInf.setSaInitTime(saInitTime);
            tblCtlMchtInfDAO.saveOrUpdate(tblCtlMchtInf);
        }
        fileInputStream.close();
        fileNameIndex++;
    }
    return Constants.SUCCESS_CODE;
}

From source file:com.bayareasoftware.chartengine.ds.util.ExcelDump.java

License:Apache License

private static void runOld(String fileName) throws Exception {
    InputStream is = new FileInputStream(fileName);
    POIFSFileSystem fs = new POIFSFileSystem(is);
    HSSFWorkbook wb = new HSSFWorkbook(fs);
    HSSFSheet sheet = wb.getSheetAt(0);
    int firstRow = sheet.getFirstRowNum();
    int lastRow = sheet.getLastRowNum();
    p("first/last row: " + firstRow + "/" + lastRow);
    HSSFRow[] rows = new HSSFRow[lastRow + 1];
    int maxFirstCell = 0, maxLastCell = 0;
    for (int i = firstRow; i <= lastRow; i++) {
        HSSFRow r = sheet.getRow(i);//from   w ww. j  a v a 2  s. c o  m
        if (r != null) {
            rows[i] = r;
            maxFirstCell = Math.max(maxFirstCell, r.getFirstCellNum());
            maxLastCell = Math.max(maxLastCell, r.getLastCellNum());

        }
    }
    p("maxFirstCell=" + maxFirstCell + ", maxLastCell=" + maxLastCell);

    StringBuilder table = new StringBuilder();
    table.append("<html><head><style>\n");
    table.append("body,td { font-family: monospaced; font-size: 12 }\n");
    table.append("</style></head>");
    table.append("<p>maxFirstCell=" + maxFirstCell + " maxLastCell=" + maxLastCell + "</p>");
    table.append("<table border=\"1\">");
    for (int i = firstRow; i <= lastRow; i++) {
        HSSFRow r = sheet.getRow(i);
        if (r == null) {
            System.err.println("NULL row at " + i);
        }
        table.append(row2string(r, maxLastCell));
    }
    table.append("</table></body></html>");
    File f = new File("sheet.html");
    Writer w = new FileWriter(f);
    w.write(table.toString());
    w.close();
    p("saved to " + f.getAbsolutePath());
}

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

License:Open Source License

public static DefaultTableModel splitExcelFile(File toSplit, int acceptFormula, int tableIndex,
        boolean convertCharsToEntites) throws Exception {

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

    if (tableIndex > -1) {
        HSSFSheet sheet = wb.getSheetAt(tableIndex - 1);

        boolean isBlankRow = true;

        int numCols = 0;
        int numRows = 0;
        ////www . j av a  2s.co  m
        //int firstRow = 0;
        int firstColumn = 0;
        int iColumn = 0;
        //firstRow = getFirstRow(sheet,-1);

        /*if(firstRow==-1) {
         //MessageHandler.showError("Error, Cannot Read Sheet: "+tableIndex,"Import From Excel Error");
          return(null);
          }
          else {*/
        HSSFRow row = sheet.getRow(sheet.getFirstRowNum());
        firstColumn = getFirstColumn(sheet);

        numCols = getNumberOfCells(sheet);

        //row = sheet.getRow(firstRow);
        //numRows = sheet.getLastRowNum() - firstRow;

        Vector rows = new Vector();
        /*System.out.println(firstColumn+":"+numCols);
         System.out.println(sheet.getFirstRowNum()+" To "+sheet.getLastRowNum());
         System.out.println(sheet.getPhysicalNumberOfRows());*/
        for (int rCnt = sheet.getFirstRowNum(); rCnt < sheet.getPhysicalNumberOfRows(); ++rCnt) {
            //reset the blank row boolean
            isBlankRow = true;

            row = sheet.getRow(rCnt);
            //System.out.println(numCols + ":" + firstColumn);
            String[] separated = new String[numCols - firstColumn];

            for (int cCnt = firstColumn; cCnt < numCols; ++cCnt) {
                try {
                    HSSFCell cell = row.getCell((short) cCnt);
                    if (cell != null) {
                        switch (cell.getCellType()) {

                        case HSSFCell.CELL_TYPE_NUMERIC://System.out.println(rCnt+":"+cCnt+ " is numeric");

                            double value = row.getCell((short) cCnt).getNumericCellValue();

                            try {
                                //get the long value which eliminates the decimal point
                                long iValue = (new Double(value)).longValue();
                                //get the double value from this long value
                                double longValue = (new Long(iValue)).doubleValue();
                                //subtract the two, if answer is 0 then
                                //value can be converted,
                                //if not then it can't
                                if (value - longValue == 0) {
                                    //use long value
                                    separated[cCnt - firstColumn] = String.valueOf(iValue);
                                } //end if
                                else {
                                    //use double value
                                    separated[cCnt - firstColumn] = String.valueOf(value);
                                } //end else
                            } //end try
                            catch (NumberFormatException e) {
                                //use double value
                                separated[cCnt - firstColumn] = String.valueOf(value);
                            } //end catch

                            break;

                        case HSSFCell.CELL_TYPE_STRING://System.out.println(rCnt+":"+cCnt+ " is string");

                            isBlankRow = false;
                            separated[cCnt - firstColumn] = row.getCell((short) cCnt).getStringCellValue();

                            break;

                        case HSSFCell.CELL_TYPE_FORMULA://System.out.println(rCnt+":"+cCnt+ " is formula");

                            isBlankRow = false;
                            if (acceptFormula == 0) {
                                //prompt
                                String[] options = { "Cell Value", "Formula Text" };
                                Object formulaValue = JOptionPane.showInputDialog(null,
                                        "This worksheet contains formulas\n"
                                                + "What format would you like to import "
                                                + "the formula cells by: ",
                                        "Import From Table", JOptionPane.INFORMATION_MESSAGE, null, options,
                                        options[0]);
                                if (formulaValue.toString().equalsIgnoreCase(options[0])) {
                                    //accept values
                                    acceptFormula = 2;
                                } //end if
                                else {
                                    acceptFormula = 1;
                                } //end else
                            } //end if
                            else if (acceptFormula == 1) {
                                //accept formula
                                separated[cCnt - firstColumn] = row.getCell((short) cCnt).getCellFormula();

                            } //end else
                            else if (acceptFormula == 2) {
                                //dont accept formula
                                double doubleValue = row.getCell((short) cCnt).getNumericCellValue();
                                Double dValue = new Double(doubleValue);
                                if (dValue.isNaN()) {
                                    //should have been a string
                                    separated[cCnt - firstColumn] = row.getCell((short) cCnt)
                                            .getStringCellValue();

                                } //end if
                                else {
                                    try {

                                        //get the long value which eliminates the decimal point
                                        long iValue = (new Double(doubleValue)).longValue();

                                        //get the double value from this long value
                                        double longValue = (new Long(iValue)).doubleValue();

                                        //subtract the two, if answer is 0 then
                                        //value can be converted,
                                        //if not then it can't
                                        if (doubleValue - longValue == 0) {
                                            //use long value
                                            separated[cCnt - firstColumn] = String.valueOf(iValue);

                                        } //end if
                                        else {
                                            //use double value
                                            separated[cCnt - firstColumn] = String.valueOf(doubleValue);

                                        } //end else

                                    } //end try
                                    catch (NumberFormatException e) {
                                        //use double value
                                        separated[cCnt - firstColumn] = String.valueOf(doubleValue);

                                    } //end catch
                                } //end else
                            } //end else

                            break;

                        case HSSFCell.CELL_TYPE_ERROR://System.out.println(rCnt+":"+cCnt+ " is error");

                            separated[cCnt - firstColumn] = "";

                            break;
                        case HSSFCell.CELL_TYPE_BOOLEAN://System.out.println(rCnt+":"+cCnt+ " is boolean");

                            isBlankRow = false;
                            boolean booleanValue = row.getCell((short) cCnt).getBooleanCellValue();
                            separated[cCnt - firstColumn] = String.valueOf(booleanValue);

                            break;
                        case HSSFCell.CELL_TYPE_BLANK://System.out.println(rCnt+":"+cCnt+ " is blank");

                            separated[cCnt - firstColumn] = "";

                            break;

                        }

                    } //end if cell!=null
                    else {

                    } //end else

                } catch (Exception e) {
                    //just a blank cell
                    separated[cCnt - firstColumn] = "";

                } //end try catch

            } //end for cCnt

            if (!isBlankRow) {
                rows.add(separated);
            }
            //HSSFCell cell;
        } //end for rCnt    

        DefaultTableModel tableModel = addRowsToTable(rows, numCols - firstColumn);
        /*fileName = file.getAbsolutePath();
         fileName = fileName.substring(0, fileName.lastIndexOf("."));
         fileName += ".xml";*/
        return (tableModel);

    } //end else
      //}

    return (null);

}

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

License:Open Source License

public static int getFirstColumn(HSSFSheet sheet) throws Exception {

    int minimum = 0;
    boolean isFirstTime = true;
    for (int cnt = sheet.getFirstRowNum(); cnt < sheet.getPhysicalNumberOfRows(); ++cnt) {

        //get the first row
        HSSFRow row = sheet.getRow(cnt);
        boolean found = false;
        //now find the first column that isn't null or empty
        short icnt = 0;
        while ((icnt < row.getLastCellNum()) && (found != true)) {

            try {
                HSSFCell cell = row.getCell(icnt);
                //System.out.println(icnt+":"+cell.getCellType());
                if (cell != null) {
                    //System.out.println(cell.getCellType());
                    if (icnt < minimum) {
                        minimum = icnt;/* w w w. j av  a  2  s  .  co m*/
                    }
                    if (isFirstTime) {
                        minimum = icnt;
                        isFirstTime = false;
                    }
                    found = true;

                }

            } catch (NullPointerException e) {
                // TODO Auto-generated catch block
                //System.out.println(icnt+" is null");
                e.printStackTrace();

            }
            //System.out.println("minimum for row: "+cnt+ " is "+minimum);
            ++icnt;
        }

    }

    return (minimum);
}

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

License:Open Source License

public static int getNumberOfCells(HSSFSheet sheet) throws Exception {

    int maxNumberOfCells = 0;
    for (int cnt = sheet.getFirstRowNum(); cnt < sheet.getPhysicalNumberOfRows(); ++cnt) {

        //get the first row
        HSSFRow row = sheet.getRow(cnt);
        if (row.getPhysicalNumberOfCells() > maxNumberOfCells)
            maxNumberOfCells = row.getPhysicalNumberOfCells();
    }// w  ww  . j  a v a  2s .  c  om
    return (maxNumberOfCells);
}