Reading a cell from Excel using Apache POI - java

I'm new to the Apache POI, so I'm having some trouble to use it.
I need to read an Excel file, but I don't need all the rows, because my final goal with this code is to shrink the file (that have over 900 lines) to have only the information I'll use later.
So I tried to use the following code:
public static void main(String[] args) {
List<Planejado> planejados = new ArrayList<Planejado>();
int i = 0;
int linha = 5;
try{
FileInputStream fis = new FileInputStream("C:\\Users\\fs0234\\Desktop\\Projetos\\Realizado X Planejado\\Planej. Semanal por CC do Funcionário (20).xls");
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheetAt(0);
int rowMax = sheet.getLastRowNum();
while (i <= rowMax) { // interação do excel validando pela coluna I
Row row = sheet.getRow(linha);
Cell cell = row.getCell(9);
if (cell.equals("")){ // Line 38
Planejado planejado = new Planejado();
planejado.setCentroCusto("CC - " + i); // obter valor da celula j + contador
planejado.setNomeRecurso("Recurso " + i); // obter valor da celula k + contador
for(int j = 1; j < 53; j++) { //interação das colunas w até bw
planejado.getTimecard().put("Semana" + j, 40 + j);//obter o valor das horas
}
planejados.add(planejado);
}
linha++;
i++;
}
for(Planejado planejado : planejados) {
//gravar no banco todos os objetos dentro da lista
System.err.println(planejado.getCentroCusto() + " | " + planejado.getNomeRecurso() + " | " + planejado.getTimecard().get("Semana6"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Where I need only the rows where the column 9 is empty.
But I get the Error
"Exception in thread "main" java.lang.NullPointerException
at main.PopulaPlanejado.main(PopulaPlanejado.java:38)"
Don't know if it's clear what I need to do, but I hope some of you can help me.

Instead Of using
if (cell.equals("")){
...
}
Try using this
if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
....
}
While using equals() for object comparison be careful otherwise you'll end up throwing NullPointerException. Do remember that calling any method on a null resulting object will throw a NPE.
You should remember some best practice to avoid NullPointerException.
Bad comparison
if (state.equals("OK")) {
...
}
Better comparison
if ("OK".equals(state)) {
...
}
So in the later case you don't have a chance to end up with NPE.
Hope it will help you. :)

Thank's to you and some other friend I'm was able to solve the problem.
Here is the code without bugs
List<Planejado> planejados = new ArrayList<Planejado>();
int i = 0;
int linha = 5;
try {
FileInputStream fis = new FileInputStream("C:\\Users\\fs0234\\Desktop\\Projetos\\Realizado X Planejado\\Planej. Semanal por CC do Funcionário (20).xls");
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheetAt(0);
int rowMax = sheet.getLastRowNum();
while (i <= rowMax) { // Loop até a última linha da planilha
Row row = sheet.getRow(linha);
if (row != null) { // Apenas linhas "não nulas"
Cell cell = row.getCell(8); // obter valor da celula I
if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) { //Verifica se a coluna I é nula
Cell CC = row.getCell(6); // obter valor da celula G
Cell nome = row.getCell(10); // obter valor da celula K
Planejado planejado = new Planejado();
planejado.setCentroCusto("CC - " + CC);
planejado.setNomeRecurso("Recurso - " + nome);
for (int j = 1, weekCol = 22; j <= 53; j++, weekCol++) { // Loop para pegar todas as semanas
Cell week = row.getCell(weekCol); // Obter valor da coluna da semana
if (week != null) {
planejado.getTimecard().put("Semana" + j, week.getNumericCellValue());
} else {
planejado.getTimecard().put("Semana" + j, Double.valueOf(0));
}
}
planejados.add(planejado);
}
}
linha++;
i++;
}
for (Planejado planejado : planejados) {
StringBuffer timecard = new StringBuffer();
for (int k = 1; k < 53; k++) {
timecard.append("Semana " + k);
timecard.append(": ");
timecard.append(planejado.getTimecard().get("Semana" + k));
timecard.append(", ");
}
System.err.println(planejado.getCentroCusto() + " | " + planejado.getNomeRecurso() + " | " + timecard.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Related

Problem with reading textfiles with scanner in Java and ArrayLists

I'm having a problem where I read a textfile named "songs.txt" with Scanner in a function called loadFiles() which every line is:
Music ID # Song Name # Release Date
And with this I create a Song object, and then store said object in a ArrayList. After reading the file, I clone this ArrayList so I can return a ArrayList with the songs read and clear the first ArrayList to prevent the cases where for exemple:
(PS: I use the ArrayLists as global variables)
songs.txt has this structure:
1oYYd2gnWZYrt89EBXdFiO#Message In A Bottle#1979
7zxc7dmd82nd92nskDInds#Sweet Child of Mine#1980
And the loadFiles() is called 2 times, the ArrayList would have a size of 4 instead of 2 as it should be. So that's why after songs.txt is read I copy the arrayList and then clear the first ArrayList that way the ArrayList that's returned only has the size of 2.
This is my code:
package pt.ulusofona.aed.deisiRockstar2021;
import java.io.IOException;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Main {
public static ArrayList < Song > teste6 = new ArrayList < > ();
public static ArrayList < Song > getSongsArray = new ArrayList < > ();
public static ArrayList < Artista > testeSongArtists = new ArrayList < > ();
public static ParseInfo parseInfoSongsTxT = new ParseInfo(0, 0);
public static ParseInfo parseInfoSongsArtistsTxT = new ParseInfo(0, 0);
public static ParseInfo parseInfoSongsDetailsTxT = new ParseInfo(0, 0);
public static void main(String[] args) throws IOException {
ArrayList < Song > teste7 = new ArrayList < Song > ();
loadFiles();
loadFiles();
teste7 = getSongs();
ParseInfo teste8 = getParseInfo("songs.txt");
System.out.println("\n----------------------TESTE DO MAIN----------------------");
System.out.println(teste7.toString());
System.out.println(teste8.toString());
System.out.println(getSongsArray.size());
}
public static void loadFiles() throws IOException {
//Aqui lê-se o ficheiro songs.txt
System.out.println("----------------------LEITURA DO FICHEIRO songs.txt------------");
String nomeFicheiro = "songs.txt";
try {
File ficheiro = new File(nomeFicheiro);
FileInputStream fis = new FileInputStream(ficheiro);
Scanner leitorFicheiro = new Scanner(fis);
while (leitorFicheiro.hasNextLine()) {
String linha = leitorFicheiro.nextLine();
String dados[] = linha.split("#");
if (dados.length != 3) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[2].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
//Meter para ignorar a acabar com espaço
parseInfoSongsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
String nome = dados[1];
int anoLancamento = Integer.parseInt(dados[2]);
Song song = new Song(idTemaMusical, nome, null, anoLancamento, 0, false, 0, 0, 0, 0);
teste6.add(song);
}
leitorFicheiro.close();
getSongsArray = (ArrayList < Song > ) teste6.clone();
teste6.clear();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro + " nao foi encontrado.";
System.out.println(mensagem);
}
System.out.println(teste6.toString());
System.out.println("Ok: " + parseInfoSongsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsTxT.NUM_LINHAS_IGNORED + "\n");
System.out.println("----------------------LEITURA DO FICHEIRO song_artists.txt------------");
//Aqui é lido o ficheiro song_artists.txt, mas falta ver se é preciso separar vários artistas com o mesmo ID para posições diferentes no ArrayList
String nomeFicheiro2 = "song_artists.txt";
try {
File song_artists = new File(nomeFicheiro2);
FileInputStream fis2 = new FileInputStream(song_artists);
Scanner leitorFicheiro2 = new Scanner(fis2);
while (leitorFicheiro2.hasNextLine()) {
String linha = leitorFicheiro2.nextLine();
String dados[] = linha.split("#");
if (dados.length != 2) {
parseInfoSongsArtistsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
parseInfoSongsArtistsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
String artista = dados[1];
Artista artista2 = new Artista(idTemaMusical, artista);
testeSongArtists.add(artista2);
}
leitorFicheiro2.close();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro2 + " não foi encontrado.";
System.out.println(mensagem);
}
System.out.println(testeSongArtists.toString());
System.out.println("Ok: " + parseInfoSongsArtistsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsArtistsTxT.NUM_LINHAS_IGNORED + "\n");
System.out.println("----------------------LEITURA DO FICHEIRO song_details.txt------------");
//Aqui lê-se o ficheiro song_details.txt
boolean letra = false;
ArrayList < Song > testeSongDetails = new ArrayList < Song > ();
String nomeFicheiro3 = "song_details.txt";
try {
File song_details = new File(nomeFicheiro3);
FileInputStream fis3 = new FileInputStream(song_details);
Scanner leitorFicheiro3 = new Scanner(fis3);
while (leitorFicheiro3.hasNextLine()) {
String linha = leitorFicheiro3.nextLine();
String dados[] = linha.split("#");
if (dados.length != 7) {
parseInfoSongsDetailsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[3].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[4].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[5].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[6].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
parseInfoSongsDetailsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
//System.out.println(idTemaMusical);
int duracao = Integer.parseInt(dados[1]);
//System.out.println(duracao);
int letraExplicita = Integer.parseInt(dados[2]);
//System.out.println(letraExplicita);
if (letraExplicita == 0) {
letra = false;
} else {
letra = true;
}
//System.out.println(letra);
int populariedade = Integer.parseInt(dados[3]);
//System.out.println(populariedade);
double dancabilidade = Double.parseDouble(dados[4]);
//System.out.println(dancabilidade);
double vivacidade = Double.parseDouble(dados[5]);
//System.out.println(vivacidade);
double volumeMedio = Double.parseDouble(dados[6]);
//System.out.println(volumeMedio);
Song song = new Song(idTemaMusical, null, null, 0, duracao, letra, populariedade, dancabilidade, vivacidade, volumeMedio);
testeSongDetails.add(song);
}
leitorFicheiro3.close();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro3 + " não foi encontrado.";
System.out.println(mensagem);
}
System.out.println("Ok: " + parseInfoSongsDetailsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsDetailsTxT.NUM_LINHAS_IGNORED);
}
public static ArrayList < Song > getSongs() {
return getSongsArray;
}
public static ParseInfo getParseInfo(String fileName) {
if (fileName == "songs.txt") {
return parseInfoSongsTxT;
}
if (fileName == "song_artists.txt") {
return parseInfoSongsArtistsTxT;
}
if (fileName == "song_details.txt") {
return parseInfoSongsDetailsTxT;
}
return null;
}
}
The problem is that when I made a test to check the function where the ArrayList is returned to see the size of the ArrayList it always comes as 0.
I think it's because only the function the returns the ArrayList is tested so loadFiles() isn't executed so the ArrayListo never gets cloned and that makes the ArrayList that is returned stay the same.
I thought about calling loadFiles() inside getSongs() and that way I would guarantee that the ArrayList is cloned but that would make getSongs use "throws IOException" and since I have to respect the school's project guide and getSongs doesn't include "throws IOException" i can't put it there.
But the more I think about it, that doesn't even make sense because how can they test it with a file of their own and loadFiles() isn't executed?
I'm out of ideas how to solve this problem, any help is welcome thank you.

Java array 2d array center string data type

I like to center the data of this array using Joptionpane i look at string.format and other but nothing helps i want something like all the information in the matrix its alight whit each other and a "|" to separete the information of each column
the information in data doesnt alignt
score [0][0]="Empresa "
score [0][1]="Guanacaste";
score [0][2]="Alajuela";
score [0][3]="Heredia";
score [0][4]="San Jose";
score [0][5]="Cartago";
score [0][6]="Limon";
score [0][7]="Puntarenas";
score [0][8]="Total";
score [0][9]="Porcentaje";
score [1][0]="SOIN"+" ";
score [2][0]="AVANTICA"+" ";
score [3][0]="INNOVASOFT ";
score [4][0]="CRUX"+" "+" ";
score [5][0]="NCQ"+" "+" ";
this is the array : String [][] score= new String[6][10];
public static void Output() {
int l = 0;
String data = "";
if (score[0][0] != (null)) {
while (l < score.length) {
for (int i = 0; i < 10; i++) {
if (score[l][i] == null) {
score[l][i] = "0";
}
data += " | " + score[l][i];
if (i == 9) {
data += " |";
}
}
l++;
data += "\n";
}
JOptionPane.showMessageDialog(null, data);
} else {
JOptionPane.showMessageDialog(null, "No se han ingresado datos", "Datos ingresados", JOptionPane.INFORMATION_MESSAGE);
}
}
Try something like this:
public static void output()
{
final StringBuilder data = new StringBuilder(1024).append("<html><table>");
final Formatter fmt = new Formatter(data);
if (score[0][0] != null )
{
for (int l = 0; l < score.length; ++l)
{
data.append("<tr>");
for (int i = 0; i < 10; ++i)
{
if (score[l][i] == null)
{
score[l][i] = "0";
}
fmt.format("<td>%s</td>", score[l][i]);
}
data.append("</tr>";
}
JOptionPane.showMessageDialog(null, data.toString());
}
else
{
JOptionPane.showMessageDialog(null, "No se han ingresado datos", "Datos ingresados",
JOptionPane.INFORMATION_MESSAGE);
}
}
so i find this solution
int l=0;
String [][] matriz= new String [6][10];
StringBuilder result=new StringBuilder();// this will save and output the matirz
if(score[0][0]!=null){
for(int i =0;i<6;i++){
for(int j=0;j<10;j++){
matriz[i][j]=score[i][j];
}//for columnas
}//for lineas
}//if encargado de crear matriz copia
if(score[0][0]!=(null)){
result.append("<html><font face='Arial'>");
result.append("<table>");
result.append("<tr>");
while(l<score.length ){
for(int i=0;i<10;i++){
if(score[l][i]==null){
score[l][i]="0";
}//if revisa que los datos en la matriz no seal null
//data+="| "+matriz[l][i]+" ";
result.append("|");
result.append("<td align='center'>").append(score[l][i]).append("</td>");// inserting the matrix data into result
if(i==9){
result.append(" |");
}
}//for
l++;
result.append("</tr>");
result.append("<tr>");
//result.append("\n");
}//while
JOptionPane.showMessageDialog(null,result,"Datos Ingresados",JOptionPane.INFORMATION_MESSAGE);
}//if
else{JOptionPane.showMessageDialog(null, "No se han ingresado datos","Datos Ingresados",JOptionPane.INFORMATION_MESSAGE);}

Cell and Column on XLSX Apache Java

I really have some problems with my code. Really appreciate it if any of you would help me. Below is my code and 2 screenshots of what it looks like and how it should looks like when the code is being executed.
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename="+ ReportID + ".xlsx");
String excelFileName = "C:\\Test.xlsx";
XSSFWorkbook w = new XSSFWorkbook();
System.out.println("w: " + w);
XSSFSheet s = w.createSheet(ReportID);
System.out.println("s: " + s);
// Report Title
s.createRow(0).createCell(0).setCellValue(Title);
System.out.println("Title: " + Title);
// Populate the worksheet
int _col_cnt = HeadersLabel.length;
XSSFRow row = s.createRow(_col_cnt);
System.out.println("HeadersLabel: " + _col_cnt);
for (int c = 0; c < _col_cnt; c++) {
// Construct the header row
String _h = HeadersLabel[c];
System.out.println("_h: " + _h);
if (_h != null) {
XSSFCell hd = row.createCell(c);
hd.setCellValue(_h);
}
int r = 3;
for (Iterator iter = Cells.iterator();iter.hasNext();) {
Object[] _o = (Object[]) iter.next();
currentRow = s.createRow(r);
for(int colNum = 0; colNum < _col_cnt; colNum++){
XSSFCell currentCell =currentRow.createCell(colNum);
if (CellDataType[c].equals("STRING")
|| CellDataType[c].equals("VARCHAR")) {
String _l = (String) _o[colNum];
if (_l != null) {
currentCell.setCellValue(_l);
System.out.println("Data: " + _l);
}
}
else if (CellDataType[c].equals("DOUBLE")) {
Double _D = (Double) _o[c];
if (_D != null) {
//XSSFCell cell = rowData.createCell(c);
cell.setCellValue(_D);
}
} else if (CellDataType[c].equals("INTEGER")) {
Integer _I = (Integer) _o[c];
if (_I != null) {
//XSSFCell cell = rowData.createCell(c);
cell.setCellValue(_I);
}
} else if (CellDataType[c].equals("DATE")) {
Date _aDate = (Date) _o[c];
if (_aDate != null) {
//XSSFCell cell = rowData.createCell(c);
cell.setCellValue(_aDate);
}
} else if (CellDataType[c].equals("TIMESTAMP")) {
Timestamp _aTimestamp = (Timestamp) _o[c];
Date _aDate = Timestamp2Date(_aTimestamp);
if (_aDate != null) {
//XSSFCell cell = rowData.createCell(c);
cell.setCellValue(_aDate);
}
}
r++;
}
}
FileOutputStream fos = new FileOutputStream(excelFileName);
//w.write(response.getOutputStream());
w.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
context.responseComplete();
}
The XLSX excel did not manage to capture some data. The first two column is empty when there is suppose to be data appearing. Only the third column has the data.
What it looks like now: https://www.dropbox.com/s/2vfxsootyln6qq5/Capture3.JPG What it suppose to be like: https://www.dropbox.com/s/d0yctgk4pywh140/Capture2.JPG
I am not sure about the data source... However I have tried to solve your problem As far as possible. Please change it wherever you need.
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename="+ ReportID + ".xlsx");
String excelFileName = "C:\\Test.xlsx";
XSSFWorkbook w = new XSSFWorkbook();
System.out.println("w: " + w);
XSSFSheet s = w.createSheet(ReportID);
System.out.println("s: " + s);
// Report Title
s.createRow(0).createCell(0).setCellValue(Title);
System.out.println("Title: " + Title);
// Populate the worksheet
int _col_cnt = HeadersLabel.length;
XSSFRow row = s.createRow(_col_cnt);
System.out.println("HeadersLabel: " + _col_cnt);
//For Headers
int headerRowNum = 2; //for App, ShortName, LongName
XSSFRow currentRow = s.createRow(headerRowNum);
for(int headerCol =0; headerCol <_col_cnt; headerCol++){
currentRow.createCell(headerCol).setCellValue(HeadersLabel[headerCol]);
}
// for Date entry
for(int dataRow=3;dataRow < 20;dataRow++){
currentRow = s.createRow(dataRow);
for(int colNum=0;colNum<_col_cnt;colNum++){
XSSFCell currentCell =currentRow.createCell(colNum);
if (CellDataType[c].equals("STRING") || CellDataType[c].equals("VARCHAR")) {
String _l = (String) _o[c];
if (_l != null) {
currentCell.setCellValue(_l);
}
} else if (CellDataType[c].equals("DOUBLE")) {
Double _D = (Double) _o[c];
if (_D != null) {
currentCell.setCellValue(_D);
}
} else if (CellDataType[c].equals("INTEGER")) {
Integer _I = (Integer) _o[c];
if (_I != null) {
currentCell.setCellValue(_I);
}
} else if (CellDataType[c].equals("DATE")) {
Date _aDate = (Date) _o[c];
if (_aDate != null) {
currentCell.setCellValue(_aDate);
}
} else if (CellDataType[c].equals("TIMESTAMP")) {
Timestamp _aTimestamp = (Timestamp) _o[c];
Date _aDate = Timestamp2Date(_aTimestamp);
if (_aDate != null) {
currentCell.setCellValue(_aDate);
}
}
}
}
}
}

How to remove empty rows between row data in excel using POI HSSF Library in Java

I need help to remove empty row between created list of records. i already code to remove empty rows however it able removed the first empty row only. here is the code i done:
private static void writeExcelFile(String[] keyValue, String fileName, String contents,
ArrayList<String> listProperties, ArrayList<String> listPropertiesDescription,
ArrayList<String> listPropertiesFileName) {
int rownum = 2;
HSSFSheet firstSheet;
HSSFWorkbook workbook = null;
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("Resourcebundle");
Row headerRow = firstSheet.createRow((short) 1);
headerRow.setHeightInPoints(30);
headerRow.createCell((short) 0).setCellValue("Properties Name");
headerRow.createCell((short) 1).setCellValue("Properties Description");
headerRow.createCell((short) 2).setCellValue("Properties File Name");
System.out.println("listPropertiesDescription :: " + listPropertiesDescription.size());
System.out.println("listPropertiesFileName :: " + listPropertiesFileName.size());
System.out.println("listProperties all list :: " + listProperties.toString());
System.out.println("listPropertiesDescription all list :: "
+ listPropertiesDescription.toString());
int indexProperties = 0;
for (int i = rownum; i < listProperties.size(); i++) {
// Row row = firstSheet.getRow(i + 1);
Row row = firstSheet.getRow(i);
// System.out.println("row :: " + row);
if (row == null) {
// row = firstSheet.createRow(i + 1);
row = firstSheet.createRow(i);
}
System.out.println("check index :: " + indexProperties);
for (int j = 0; j < 1; j++) {
Cell cell = row.getCell(j);
System.out.println("cell :: " + cell);
if (cell == null) {
row.createCell(j).setCellValue(
listProperties.get(indexProperties + 1).toString().trim());
row.createCell(j + 1).setCellValue(
listPropertiesDescription.get(indexProperties + 1).toString().trim());
row.createCell(j + 2).setCellValue(
listPropertiesFileName.get(indexProperties + 1).toString().trim());
}
j++;
}
indexProperties++;
System.out.println("check index below :: " + indexProperties);
i++;
}
int lastRowCount = firstSheet.getLastRowNum();
for (int i = rownum; i < lastRowCount; i++) {
HSSFRow row = firstSheet.getRow(i);
if (row == null) {
removeRow(firstSheet, i);
// firstSheet.shiftRows(i + 1, lastRowCount, -1);
// i--; // Since you move row at i+1 to i
}
}
FileOutputStream fos = null;
try {
File file = new File("OnlineHelp Master Excel.xls");
//if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
String fileRB = outputLocation.concat("\\" + file);
fos = new FileOutputStream(new File(fileRB));
workbook.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void removeRow(HSSFSheet sheet, int rowIndex) {
int lastRowNum = sheet.getLastRowNum();
if (rowIndex >= 0 && rowIndex < lastRowNum) {
sheet.shiftRows(rowIndex + 1, lastRowNum, -1);
}
if (rowIndex == lastRowNum) {
HSSFRow removingRow = sheet.getRow(rowIndex);
if (removingRow != null) {
sheet.removeRow(removingRow);
}
}
}
here i attach also result from the above code:
the results:
Row | Result
1 | result a
2 | (empty row)
3 | result b
4 | (empty row)
5 | result b
6 | (empty row)
it only able to removed empty row below result a, the rest still there.
really need help on this. thanks!
ema
I know it is a pretty old thread but ran into this problem this morning. Was not expecting HSSF library to get empty lines. So posting this answer so other members than run into it will have an answer.
Here's my solution - basically copy/paste of parts found around.
HSSFSheet sheet = new HSSFWorkbook(new ByteArrayInputStream(content)).getSheetAt(0);
int headerRowIndex = sheet.getFirstRowNum();
List<String> columnNames = getColumnNames(sheet);
List<Map<String, String>> sheetData = new ArrayList<>();
sheet.forEach(row -> {
if (row.getRowNum() != headerRowIndex && !isRowEmpty(row)) {
sheetData.add(getRowData(row, columnNames));
}
});
... And the method:
private boolean isRowEmpty(Row row) {
for (int cellIndex = row.getFirstCellNum(); cellIndex < row.getLastCellNum(); cellIndex++) {
Cell cell = row.getCell(cellIndex);
if (cell != null && cell.getCellTypeEnum() != CellType.BLANK) {
return false;
}
}
return true;
}
My test file had previously 6 empty rows. They are all gone now :) Enjoy!

Java Index Out of Bounds Exception

I'm getting an IndexOutOfBoundsException at the line that calls for my custom fonction:
motCars = remplaceTirets(motAlea, motCars, lettreDon);.
This function is supposed to turn one or more of the dashes into the letter if the given letter equals the letter in the word) and a line in the actual function where it says:
tempo += tirets.charAt(j);
The result is: _ _ _ _ _ _ _ (the amount of these dashes depends on the word chosen by the program, which works and then it asks to give a letter but when I give a letter I get:
Exception in thread 'main' java.lang.String IndexOutOfBoundsException. String Index out of range: 1.
It's partly in french because I live in Quebec. But I'm hoping that it doesn't matter because the french words just concern the strings and words, not the logic of java. I'm a beginner and overwhelmed with all the advice on all the forums on Java. Any specific advice will be welcome.
Thanks in advance for taking the time to have a look !
Anita
import java.util.Scanner;
class Tp {
public static void main( String[] args ) throws Exception {
Scanner clavier = new Scanner(System.in);
String motAlea = "";
String motCars = "";
char lettreDon = Character.UNASSIGNED;
String tempo = "";
String invite = "";
String tirets = "";
int l = 0;
int m = 0;
final String ANNONCE = "J'ai choisi un mot a deviner\n";
final String INSTRUCT = "Entrez une lettre a la fois. L'indice d'essais: 15.\n";
final String INVITE = "\tEntrez une lettre: ";
final String BRAVO = "BRAVO ! Le mot a deviner etait: ";
final String DESOLE = "DESOLE...Vous avez perdu...";
String[] vingtMots = { "WATTHEUREMETRE", "HELIOGRAPH", "GRENOUILLERE", "CONTRAROTATIF",
"CUISSARDE", "BRIGANTINE", "AVITAILLEUR", "ENTREDOUBLURE",
"GALLETAGE", "OEUILLERE", "CREMAILLERE", "HALTEROPHILIE",
"MARTINGALE", "EMPENNAGE", "ENCOCHAGE", "DECLENCHEUR",
"BIMETALLIQUE", "PIVOTEMENT", "DECLINAISON", "CROISILLON"
}; // tableau string
int indexAlea = 0;
indexAlea = (int)(Math.random() * 20) + 1;
motAlea = vingtMots[indexAlea];
for (l = 0; l < motAlea.length(); l++) {
tempo += "_";
motCars = tempo;
} // for
System.out.print(ANNONCE);
System.out.print(INSTRUCT);
l = 0;
do {
if (motCars.equals(motAlea)) {
System.out.print(BRAVO + motAlea + ", " + "devine en " + m +
" tentatives");
System.exit(0);
} // if
if (l == 15) {
System.out.print("\n" + DESOLE + "Le mot a devine etait: " +
motAlea + ". " + "Au revoir... ");
System.exit(0);
} // if
for (int i = 0; i < motAlea.length(); i++) {
System.out.print(motCars.charAt(i) + " ");
} // for
m = l + 1;
invite = "\t" + INVITE + m + "> :";
lettreDon = lecture(invite);
motCars = remplaceTirets(motAlea, motCars, lettreDon);
l++;
} // do
while (l < 16); {
System.out.print("\n" + DESOLE + "Le mot a devine etait: " + motAlea + ". "
+ "Au revoir... ");
} // while
} //main(...)
public static char lecture(String invite1){
Scanner clavier = new Scanner(System.in);
final String ERREUR = "La valeur entree est erronnee !\nReprenez-vous...";
final String VIDE = " ";
String retour = "";
do {
try {
System.out.print(invite1);
retour = clavier.nextLine().trim(); // Mise en forme;
for (int k = 0; k < retour.length(); k++) {
if(Character.isLetter(retour.charAt(k))) {
return retour.toUpperCase().charAt(0);
} // if
} // for
} // try
catch (Exception e) {
System.out.print(ERREUR);
}
}// do
while (!retour.equals(VIDE)); {
retour = "X";
return retour.charAt(0);
} // while
} // lecture(...)
public static String remplaceTirets(String motAlea1, String tirets,
char lettre) {
String retour;
String tempo = "";
for (int j = 0; j < motAlea1.length(); j++) {
String lettre1 = Character.toString(lettre);
if (motAlea1.charAt(j) != lettre1.charAt(0)) {
tempo += tirets.charAt(j);
} // if
else {
tempo += lettre1.charAt(0);
} // else
tirets = tempo;
} // for
return retour = tirets;
} //remplaceTirets(...)
}//Tp
The line
tirets = tempo;
should be out of the for loop.
change your code to
for (int j = 0; j < motAlea1.length(); j++) {
String lettre1 = Character.toString(lettre);
if (motAlea1.charAt(j) != lettre1.charAt(0)) {
tempo += tirets.charAt(j);
} // if
else {
tempo += lettre1.charAt(0);
} // else
//tirets = tempo; //REMOVE THIS LINE
} // for
tirets = tempo; //ADD THIS LINE
You are accessing a position in tirets based on the length of motAlea1. I expect that motAlea1.length() > tirets.length().
for (int j = 0; j < motAlea1.length(); j++) {
String lettre1 = Character.toString(lettre);
if (motAlea1.charAt(j) != lettre1.charAt(0)) {
tempo += tirets.charAt(j); //THIS COULD FAIL!!!
}else{
tempo += lettre1.charAt(0);
}
tirets = tempo;
}
In this loop:
for (int j = 0; j < motAlea1.length(); j++) {
String lettre1 = Character.toString(lettre);
if (motAlea1.charAt(j) != lettre1.charAt(0)) {
tempo += tirets.charAt(j);
} // if
else {
tempo += lettre1.charAt(0);
} // else
tirets = tempo;
} // for
String tirets is shorter than motAlea1 and so you're trying to retrieve a character beyond its end.

Categories

Resources