List of usage examples for org.apache.poi.hssf.usermodel HSSFWorkbook getSheetAt
@Override public HSSFSheet getSheetAt(int index)
From source file:beans.ReviewsBeans.java
public void postProcessXLS(Object document) { HSSFWorkbook wb = (HSSFWorkbook) document; HSSFSheet sheet = wb.getSheetAt(0); CellStyle style = wb.createCellStyle(); style.setFillBackgroundColor(IndexedColors.AQUA.getIndex()); for (Row row : sheet) { for (Cell cell : row) { cell.setCellValue(cell.getStringCellValue().toUpperCase()); cell.setCellStyle(style);/* ww w.j ava 2 s. c o m*/ } } }
From source file:br.com.nfsconsultoria.azcontrole.bean.VendaBean.java
public void postProcessXLS(Object document) { HSSFWorkbook wb = (HSSFWorkbook) document; HSSFSheet sheet = wb.getSheetAt(0); HSSFRow header = sheet.getRow(0);/* w w w . java 2 s .c o m*/ HSSFFont font = wb.createFont(); font.setBold(true); font.setColor(HSSFColor.WHITE.index); HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index); cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); cellStyle.setWrapText(true); cellStyle.setAlignment(CellStyle.ALIGN_JUSTIFY); cellStyle.setFont(font); for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) { HSSFCell cell = header.getCell(i); cell.setCellStyle(cellStyle); } }
From source file:br.com.primetestes.TableBean.java
License:Apache License
public void postProcessXLS(Object document) { HSSFWorkbook wb = (HSSFWorkbook) document; HSSFSheet sheet = wb.getSheetAt(0); HSSFRow header = sheet.getRow(0);/*w w w.j av a2 s.c om*/ HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setFillForegroundColor(HSSFColor.GREEN.index); cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) { HSSFCell cell = header.getCell(i); cell.setCellStyle(cellStyle); //TODO fucking fix that HSSCell class pls } }
From source file:br.eti.rogerioaguilar.minhasclasses.util.excel.leitor.LeitorExcel.java
License:Open Source License
/** * Realiza o processamento de leitura seguindo o fluxo: * /*ww w .j av a2 s . c om*/ * 1 - O leitor abre a planilha <br> * 2 - o leitor comea a ler as linhas e colunas da planilha <br> * 3 - Para cada linha encontrada: <br> * 3.1 - Caso a linha esteja na lista de linhas que devem ser processadas passada ao construtor: <br> * 3.1.1 - O leitor monta uma lista de vos contendos os dados das colunas para a linha atual que <br> * estejam dentro do padro de leitura passado ao construtor <br> * 3.1.2 - O leitor chama o mtodo LinhaListener.lendoLinha passando o mapa com os dados da linha <br> * e aguarda o final do processamento. <br> * 3.1.2.1 - Caso o mtodo do listener retorne true, o leitor continua o processamento da <br> * da planilha. Caso contrrio, o processamento da planilha interrompido <br> * Se o processamento da planilha continuar (de acordo com o parmetro de retorno <br> * do listener para a linha descrito anteriormente), o leitor chama o listener para <br> * a coluna para cada coluna da linha atual. O comportamento deste listener o mesmo <br> * do listener para a linha, ou seja, se o listener retornar false o processamento da <br> * planilha interrompido. * * @throws ParseException * @throws PlanilhaNaoEncontradaException caso o ndice da planilha no seja encontrado no arquivo * @throws FileNotFoundException caso o arquivo passado como parmetro no exista * @throws ListenerException caso ocorra algum erro na chamada de algum dos listeners * @throws IOException caso ocorra algum problema de io * */ public void processarLeituraPlanilha() throws ParseException, PlanilhaNaoEncontradaException, FileNotFoundException, IOException, ListenerException { try { log.debug("Inicializando o processamento da leitura do arquivo..."); log.debug("Dados para o processamento --> " + this); POIFSFileSystem fs = null; if (this.streamArquivo != null) { fs = new POIFSFileSystem(streamArquivo); } else if (this.caminhoArquivoExcel != null) { fs = new POIFSFileSystem(new FileInputStream(this.caminhoArquivoExcel)); } else { throw new IllegalArgumentException( "No foi definido um stream para o arquivo nem um caminho para o arquivo!"); } log.debug("Processando a string de entrada --> " + this.strPadraoLeitura); Map mapaLinhasAProcessar = LeitorExcelReader .getMapaEntradas(new ByteArrayInputStream(this.strPadraoLeitura.getBytes())); log.debug("A string de entrada --> " + this.strPadraoLeitura + " foi processada com sucesso."); log.debug("Mapa retornado --> " + mapaLinhasAProcessar); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet planilha = wb.getSheetAt(this.indicePlanilha - 1); if (planilha == null) { log.error("Planilha no encontrada no ndice -->" + this.indicePlanilha); throw new PlanilhaNaoEncontradaException( "Planilha no encontrada no ndice -->" + this.indicePlanilha); } else { log.debug("A string de entrada --> " + this.strPadraoLeitura + " foi processada com sucesso."); boolean processarTodasAsLinhas = (mapaLinhasAProcessar.get("*") != null); boolean processarTodasAsColunas = false; boolean continuarProcessamentoLinha = true; Map propriedadesListenerLinha = new HashMap(); Map propriedadesListenerColuna = new HashMap(); List listaColunas = null; List listaVosColunas = new LinkedList(); if (processarTodasAsLinhas) { log.debug("Processando todas as linhas..."); } Iterator itLinhas = planilha.rowIterator(); while (itLinhas.hasNext() && continuarProcessamentoLinha) { HSSFRow linha = (HSSFRow) itLinhas.next(); propriedadesListenerLinha.clear(); listaVosColunas.clear(); propriedadesListenerLinha.put(LinhaListener.CHAVE_LINHA_OBJETO_ORIGINAL_POI, linha); int intLinhaAtual = linha.getRowNum() + 1; log.debug("Processando linha --> " + intLinhaAtual); if (!processarTodasAsLinhas) { listaColunas = getListaColunasLinha("" + intLinhaAtual, mapaLinhasAProcessar); } else { listaColunas = getListaColunasLinha("*", mapaLinhasAProcessar); } boolean processarLinhaAtual = processarTodasAsLinhas || (listaColunas != null); if (processarLinhaAtual) { Iterator itColunas = linha.cellIterator(); processarTodasAsColunas = (listaColunas != null) && (listaColunas.size() > 0) && ("" + listaColunas.get(0)).equals("*"); while (itColunas.hasNext()) { HSSFCell celula = (HSSFCell) itColunas.next(); int intCelulaAtual = celula.getCellNum() + 1; boolean processarColunaAtual = processarTodasAsColunas || ((listaColunas != null) && (listaColunas.size() > 0) && listaColunas.indexOf(new Long(intCelulaAtual)) != -1); LinhaColunaListenerVo linhaColunaListenerVo = new LinhaColunaListenerVo(); linhaColunaListenerVo.setLinha(intLinhaAtual); linhaColunaListenerVo.setColuna(intCelulaAtual); linhaColunaListenerVo.setCelulaAtual(celula); if (processarColunaAtual) { if (celula != null) { log.debug("Coluna --> " + intCelulaAtual + " para a linha --> " + intLinhaAtual + " deve ser processada..."); switch (celula.getCellType()) { case HSSFCell.CELL_TYPE_STRING: linhaColunaListenerVo.setValorStr(celula.getStringCellValue()); break; case HSSFCell.CELL_TYPE_NUMERIC: linhaColunaListenerVo .setValorNumerico(new Double(celula.getNumericCellValue())); break; case HSSFCell.CELL_TYPE_FORMULA: linhaColunaListenerVo.setCelulaFormula(true); linhaColunaListenerVo.setValorStrFormula(celula.getCellFormula()); break; case HSSFCell.CELL_TYPE_ERROR: linhaColunaListenerVo.setCelulaContemErro(true); linhaColunaListenerVo.setErro(new Byte(celula.getErrorCellValue())); break; case HSSFCell.CELL_TYPE_BOOLEAN: linhaColunaListenerVo .setValorBoolean(new Boolean(celula.getBooleanCellValue())); break; case HSSFCell.CELL_TYPE_BLANK: linhaColunaListenerVo.setCelulaBranca(true); linhaColunaListenerVo.setValorStr(""); break; } } else { log.warn("Clula nula!"); linhaColunaListenerVo.setCelulaNula(true); } listaVosColunas.add(linhaColunaListenerVo); } else { log.debug("Coluna --> " + intCelulaAtual + " para a linha --> " + intLinhaAtual + " no deve ser processada..."); } } if (this.linhaListener != null) { log.debug("Chamando o listener para a linha --> " + intLinhaAtual); Collections.sort(listaVosColunas, new Comparator() { public int compare(Object arg0, Object arg1) { int colunaUm = ((LinhaColunaListenerVo) arg0).getColuna(); int colunaDois = ((LinhaColunaListenerVo) arg1).getColuna(); if (colunaUm < colunaDois) { return -1; } else if (colunaUm > colunaDois) { return 1; } return 0; } }); propriedadesListenerLinha.put(LinhaListener.LISTA_VOS_LINHA, listaVosColunas); continuarProcessamentoLinha = this.linhaListener.lendoLinha(intLinhaAtual, propriedadesListenerLinha); if (!continuarProcessamentoLinha) { log.debug( "Listener retornou boolean false indicando que o processamento deve ser interrompido!"); } } else { log.debug("Listener no configurado para a linha --> " + intLinhaAtual); } if (this.colunaListener != null) { Iterator itColunasVoListener = listaVosColunas.iterator(); boolean continuarProcessamentoColunasnaLinha = true; while (itColunasVoListener.hasNext() && continuarProcessamentoColunasnaLinha) { propriedadesListenerColuna.clear(); LinhaColunaListenerVo voAtual = (LinhaColunaListenerVo) itColunasVoListener.next(); propriedadesListenerColuna.put(ColunaListener.CHAVE_VO_COLUNA, voAtual); propriedadesListenerColuna.put(ColunaListener.CHAVE_COLUNA_OBJETO_ORIGINAL_POI, voAtual.getCelulaAtual()); log.debug("Chamando o listener para a coluna --> " + voAtual.getColuna() + " na linha " + voAtual.getLinha()); continuarProcessamentoColunasnaLinha = this.colunaListener.lendoColuna( voAtual.getLinha(), voAtual.getColuna(), propriedadesListenerColuna); if (!continuarProcessamentoColunasnaLinha) { log.debug( "Listener de coluna retornou boolean false indicando que o processamento das colunas na linha " + voAtual.getLinha() + " deve ser interrompido!"); } } } else { log.debug("Listener no configurado para processamento das colunas"); } } else { log.debug("Linha --> " + intLinhaAtual + " no ser processada!"); } } } log.debug("Processamento da planilha realizado com sucesso!"); } catch (ParseException e) { e.printStackTrace(); log.error("Erro ao processar a string de entrada ", e); throw e; } catch (FileNotFoundException e) { e.printStackTrace(); log.error("Arquivo " + this.caminhoArquivoExcel + " no encontrado", e); throw e; } catch (IOException e) { e.printStackTrace(); log.error("Erro ao abrir o arquivo " + this.caminhoArquivoExcel, e); throw e; } catch (ListenerException e) { e.printStackTrace(); log.error("Erro ao processar o listener ", e); throw e; } }
From source file:br.luck.managerbean.PrincipalBean.java
/*** * Exporta para arquivo xls//from w w w . ja va 2 s . co m * @param document */ public void postProcessXLS(Object document) { HSSFWorkbook wb = (HSSFWorkbook) document; HSSFSheet sheet = wb.getSheetAt(0); HSSFRow header = sheet.getRow(0); HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setFillForegroundColor(HSSFColor.GREEN.index); cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) { HSSFCell cell = header.getCell(i); cell.setCellStyle(cellStyle); } }
From source file:br.rio.puc.inf.les.controller.ApartamentoBean.java
public void postProcessXLS(Object document) { HSSFWorkbook wb = (HSSFWorkbook) document; HSSFSheet sheet = wb.getSheetAt(0); HSSFRow header = sheet.getRow(0);/*from w w w .j a v a2 s. c o m*/ HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setFillForegroundColor(HSSFColor.GREEN.index); cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) { HSSFCell cell = header.getCell(i); cell.setCellStyle(cellStyle); } }
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 .j a 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.solutio.licita.servico.ServicoSessao.java
@Override public boolean filtraPlanilha(UploadedFile uploadArquivo) { HSSFWorkbook wb = null; try {/* ww w .j av a2 s . c o m*/ wb = new HSSFWorkbook(uploadArquivo.getInputstream()); } catch (IOException ex) { Logger.getLogger(ControladorSessao.class.getName()).log(Level.SEVERE, "Error InputStream ArquivoProposta", ex); } HSSFSheet planilha = wb.getSheetAt(0); Logger.getLogger(ControladorSessao.class.getName()).log(Level.INFO, " TAMANHO DA PLANILHA: {0}", planilha.getLastRowNum()); //Indica o numero da coluna onde inicia os valores que sero retirado int indInicioValores = 6; // +1, devido a necessidade de contar mais uma coluna propostas = new Double[(planilha.getLastRowNum() + 1) - indInicioValores][2]; for (int i = 6; i <= planilha.getLastRowNum(); i++) { HSSFRow linha = planilha.getRow(i); String conversao = linha.getCell(0).getStringCellValue(); Double convertido = Double.parseDouble(conversao); propostas[i - indInicioValores][0] = convertido; propostas[i - indInicioValores][1] = linha.getCell(5).getNumericCellValue(); numTable.add(linha.getCell(5).getNumericCellValue()); Logger.getLogger(ControladorSessao.class.getName()).log(Level.INFO, numTable.toString()); } return !numTable.isEmpty(); }
From source file:browsermator.com.MyTable.java
MyTable(String csvFile) { DataFile = csvFile;// www . ja va 2s .c o m DataTable = new JTable(); myEntries = new ArrayList<>(); File filecheck = new File(csvFile); if (filecheck.isAbsolute()) { String[] left_right_side_of_dot = csvFile.split("\\."); String file_extension = left_right_side_of_dot[left_right_side_of_dot.length - 1]; switch (file_extension) { case "xls": try { FileInputStream file = new FileInputStream(new File(DataFile)); HSSFWorkbook workbook = new HSSFWorkbook(file); //Get first sheet from the workbook HSSFSheet sheet = workbook.getSheetAt(0); //Iterate through each rows from first sheet Iterator<Row> rowIterator = sheet.iterator(); int number_of_cells = 0; while (rowIterator.hasNext()) { Row row = rowIterator.next(); int number_of_thesecells = row.getPhysicalNumberOfCells(); if (number_of_thesecells > number_of_cells) { number_of_cells = number_of_thesecells; } } Iterator<Row> rowIterator2 = sheet.iterator(); while (rowIterator2.hasNext()) { Row row = rowIterator2.next(); String[] myRow = new String[number_of_cells]; Iterator<Cell> cellIterator = row.cellIterator(); int cell_index = 0; while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: Boolean boolvalue = cell.getBooleanCellValue(); String cellvalue = "false"; if (boolvalue) { cellvalue = "true"; } else myRow[cell_index] = cellvalue; break; case Cell.CELL_TYPE_NUMERIC: myRow[cell_index] = Double.toString(cell.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: myRow[cell_index] = cell.getRichStringCellValue().getString(); break; case Cell.CELL_TYPE_BLANK: myRow[cell_index] = ""; break; case Cell.CELL_TYPE_ERROR: myRow[cell_index] = ""; break; case Cell.CELL_TYPE_FORMULA: myRow[cell_index] = cell.getCellFormula(); break; } cell_index++; } if (cell_index != number_of_cells) { for (int x = cell_index; x < number_of_cells; x++) myRow[cell_index] = ""; } myEntries.add(myRow); } file.close(); } catch (Exception e) { System.out.println("Error occurred while reading XLS file: " + e.toString()); } break; case "xlsx": try { FileInputStream file = new FileInputStream(new File(DataFile)); XSSFWorkbook workbook = new XSSFWorkbook(file); //Get first sheet from the workbook XSSFSheet sheet = workbook.getSheetAt(0); //Iterate through each rows from first sheet Iterator<Row> rowIterator = sheet.iterator(); int number_of_cells = 0; while (rowIterator.hasNext()) { Row row = rowIterator.next(); int number_of_thesecells = row.getPhysicalNumberOfCells(); if (number_of_thesecells > number_of_cells) { number_of_cells = number_of_thesecells; } } Iterator<Row> rowIterator2 = sheet.iterator(); while (rowIterator2.hasNext()) { Row row = rowIterator2.next(); String[] myRow = new String[number_of_cells]; Iterator<Cell> cellIterator = row.cellIterator(); int cell_index = 0; while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: Boolean boolvalue = cell.getBooleanCellValue(); String cellvalue = "false"; if (boolvalue) { cellvalue = "true"; } else myRow[cell_index] = cellvalue; break; case Cell.CELL_TYPE_NUMERIC: myRow[cell_index] = Double.toString(cell.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: myRow[cell_index] = cell.getRichStringCellValue().getString(); break; case Cell.CELL_TYPE_BLANK: myRow[cell_index] = ""; break; case Cell.CELL_TYPE_ERROR: myRow[cell_index] = ""; break; case Cell.CELL_TYPE_FORMULA: myRow[cell_index] = cell.getCellFormula(); break; } cell_index++; } if (cell_index != number_of_cells) { for (int x = cell_index; x < number_of_cells; x++) myRow[cell_index] = ""; } myEntries.add(myRow); } file.close(); } catch (Exception ex) { System.out.print("Exception during XLSX import: " + ex.toString()); } break; case "csv": try { CSVFileReader = new CSVReader(new FileReader(DataFile), ',', '"', '\0'); myEntries = CSVFileReader.readAll(); } catch (Exception e) { } } columnnames = (String[]) myEntries.get(0); DefaultTableModel tableModel = new DefaultTableModel(columnnames, myEntries.size() - 1); rowcount = tableModel.getRowCount(); this.number_of_records = rowcount; for (int x = 0; x < rowcount + 1; x++) { int columnnumber = 0; if (x > 0) { for (String thiscellvalue : (String[]) myEntries.get(x)) { tableModel.setValueAt(thiscellvalue, x - 1, columnnumber); columnnumber++; } } } DataTable = new JTable(tableModel); int number_of_rows = DataTable.getRowCount(); if (number_of_rows < 20) { DataTable.setPreferredScrollableViewportSize( new Dimension(1200, number_of_rows * DataTable.getRowHeight())); } } else { columnnames[0] = "Stored URL List:" + csvFile; DefaultTableModel tableModel = new DefaultTableModel(columnnames, 0); DataTable = new JTable(tableModel); DataTable.getColumnModel().getColumn(0).setPreferredWidth(200); DataTable.setPreferredScrollableViewportSize(new Dimension(20, 0)); } }
From source file:bs.compra.proceso.ActualizarPreciosCostoBean.java
public void procesarArchivoExcel() { try {/*from ww w.jav a 2 s.co m*/ FileInputStream file = new FileInputStream(new File(pathArchivoExcel)); String[] split = pathArchivoExcel.split("\\."); String extension = split[split.length - 1].toLowerCase(); if (extension.equals("xls")) { HSSFWorkbook workbook = new HSSFWorkbook(file); HSSFSheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); leerDatosExcel(rowIterator); } else if (extension.equals("xls")) { XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); leerDatosExcel(rowIterator); } else { JsfUtil.addErrorMessage( "Formato de archivo incorrecto. El archivo debe tener extensin xls o xlsx"); } } catch (IOException ex) { Logger.getLogger(ActualizarPreciosCostoBean.class.getName()).log(Level.SEVERE, null, ex); } }