I'm trying to create one workbook with multiple sheets, but always getting only one row in each excel sheet, which is last line in the source file. My code is working as follows:
public void parse()
{
BufferedReader reader = null;
BufferedWriter writer = null;
String tmpFile = "tmpFile.tmp";
ExcelFile excelFile = new ExcelFile(_fileName + ".xlsx");
int lineCount = 0;
try
{
reader = new BufferedReader(new FileReader(_fileName));
writer = new BufferedWriter(new FileWriter(tmpFile));
String line = null;
while ( (line = reader.readLine()) != null)
{
String newLine = processLine(line.trim());
if (newLine == null)
continue;
else
{
if (newLine.isEmpty() )
{
lineCount++;
if(lineCount > 1)
{
continue;
}
}
else if (!newLine.isEmpty())
{
lineCount = 0;
}
if (getRepositoryName(newLine) != null && !getRepositoryName(newLine).isEmpty() )
excelFile.writeLine(getRepositoryName(newLine), newLine);
}
}
reader.close();
excelFile.createFile(_fileName.split("\\.")[0]);
}
catch (IOException e) {
e.printStackTrace();
}
}
the creation of each row done by: excelFile.writeLine(getRepositoryName(newLine), newLine); from previous method.
writeLine in ExcelFile class implemented as follows:
public void writeLine(String sheetName, String line)
{
HSSFSheet sheet = getSheet2(sheetName);
HSSFSheet sheetMain = getSheet2(_mainSheetName);
HSSFRow row = sheet.createRow(sheet.getLastRowNum() == 0 ? 0 :sheet.getLastRowNum()+1);
HSSFRow rowMain = sheetMain.createRow(sheetMain.getLastRowNum() == 0 ? 0 :sheetMain.getLastRowNum()+1);
String[] columnsArr = line.split(",");
for (int i = 0; i < columnsArr.length ; i++)
{
HSSFCell cell = row.createCell(i);
HSSFCell cellMain = rowMain.createCell(i);
cell.setCellValue(columnsArr[i]);
cellMain.setCellValue(columnsArr[i]);
}
}
Need to know what I'm doing wrong, and if it's possible to create multiple row when not running in a loop.
Thanks in advance!
Problem is in lines:
First time method
sheet.getLastRowNum()
returns0
, sosheet.createRow
is given0
as an argument. But next time result is the same and you again create row0
(and that is the same in each iteration of the loop).From the javadoc of
getLastRowNum()
:So something like this should work: