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);
}
}
}
}
}
}
Related
I am writing existing excel by merging many excel files, after generating of final excel file blank row is adding up after headers.
Below is my code which reads data from multiple files and write to particular blank file which have pivot formulas set.
I tried even by
1. Setting createRow(0) , then started filling data from next row.
2. Tried of maintaining int counter, but still didn't work
3. Tried incrementing getLastRowNum() count, but no use
public class DCSReadImpl implements ReadBehavior {
Logger log = Logger.getLogger(DCSReadImpl.class.getName());
#SuppressWarnings("resource")
#Override
public Sheet readReport(Workbook workbook,Map<String,String> masterMap, Properties properties) {
//int firstRow = 0;
int outRowCounter = 0;
String fileToMove= "";
boolean headers = true;
Row outputRow = null;
Sheet outputSheet = null;
Workbook wb = new XSSFWorkbook();
try {
outputSheet = wb.createSheet("Data");
log.info("**** Set headers start"); // this used to be different method
int cellNo = 0;
outputRow = outputSheet.createRow(0);
for(String headerName : ReportConstants.DCS_OUTPUT_HEADER){
outputRow.createCell(cellNo).setCellValue(headerName);
cellNo++;
}
//outRowCounter++;
log.info("**** Set headers completed");
log.info("Read input file(s) for DCS report");
log.info("Input File Path : " + properties.getProperty(ReportConstants.DCS_INPUT_PATH));
File inputDir = new File(properties.getProperty(ReportConstants.DCS_INPUT_PATH));
File[] dirListing = inputDir.listFiles();
if (0 == dirListing.length) {
throw new Exception(properties.getProperty(ReportConstants.DCS_INPUT_PATH) + " is empty");
}
for (File file : dirListing) {
log.info("Processing : " + file.getName());
fileToMove = file.getName();
XSSFWorkbook inputWorkbook = null;
try {
inputWorkbook = new XSSFWorkbook(new FileInputStream(file));
} catch (Exception e) {
throw new Exception("File is already open, please close the file");
}
XSSFSheet inputsheet = inputWorkbook.getSheet("Sheet1");
Iterator<Row> rowItr = inputsheet.iterator();
int headItr = 0;
//log.info("Validating headers : " + file.getName());
while (rowItr.hasNext()) {
Row irow = rowItr.next();
Iterator<Cell> cellItr = irow.cellIterator();
int cellIntItr = 0;
String key = "";
int rowN = outputSheet.getLastRowNum() + 1;
outputRow = outputSheet.createRow(rowN);
Cell outCell = null;
while (cellItr.hasNext()) {
Cell inputCell = cellItr.next();
if (0 == inputCell.getRowIndex()) {
if (!FileUtility.checkHeaders(headItr, inputCell.getStringCellValue().trim(),
ReportConstants.DCS_INPUT_HEADER)) {
throw new Exception("Incorrect header(s) present in Input File, Expected : "
+ ReportConstants.DCS_INPUT_HEADER[headItr]);
}
headItr++;
} else {
//outCell = outputRow.createCell(cellIntItr);
if (0 == inputCell.getColumnIndex()) {
key = inputCell.getStringCellValue().trim();
} else if (2 == inputCell.getColumnIndex()) {
key = key + ReportConstants.DEL + inputCell.getStringCellValue().trim();
}
if (7 == cellIntItr){
outCell = outputRow.createCell(cellIntItr);
outCell.setCellValue(getValue(masterMap, key, 0));
cellIntItr++;
outCell = outputRow.createCell(cellIntItr);
outCell.setCellValue(getValue(masterMap, key, 1));
cellIntItr++;
outCell = outputRow.createCell(cellIntItr);
outCell.setCellValue(getValue(masterMap, key, 2));
cellIntItr++;
}
// Check the cell type and format accordingly
switch (inputCell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
outCell = outputRow.createCell(cellIntItr);
outCell.setCellValue(inputCell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
outCell = outputRow.createCell(cellIntItr);
outCell.setCellValue(inputCell.getStringCellValue().trim());
break;
}
cellIntItr++;
}
}
//outRowCounter ++ ;
}
if(!fileToMove.isEmpty()){
FileUtility.checkDestinationDir(""+properties.get(ReportConstants.DCS_ARCHIVE_PATH));
FileUtility.moveFile(properties.get(ReportConstants.DCS_INPUT_PATH) + fileToMove,
properties.get(ReportConstants.DCS_ARCHIVE_PATH)+fileToMove+FileUtility.getPattern());
}
}
} catch (Exception e) {
log.error("Exception occured : ", e);
}
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream("D:\\DCS\\Output\\Krsna_"+FileUtility.getPattern()+".xlsx");
wb.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
}
return outputSheet;
}
private String getValue(Map<String, String> masterMap, String cellKey, int index) {
String value = masterMap.get(cellKey);
if (null != value) {
String cellValue[] = value.split("\\" + ReportConstants.DEL);
return cellValue[index];
} else {
return "";
}
}
}
There should not be blank row after header row. That is in between of 0th row and 1st row (hope my understanding is correct on row indexing). I know this is very basic question :-(
I have been working on a highlighting cells in excel sheet after end of execution when i opened the processed file(.xlsx file) using Ms-excel-2007 i am facing two pop up's .here the specified code and images :
HSSFWorkbook xlsWB = new HSSFWorkbook(file1InputStream);
XSSFWorkbook xlsxWB = new XSSFWorkbook(file2InputStream);
CellStyle xlsxStyle = getCellStyle(xlsxWB);
int numbeoOfSheetsFile1 = xlsWB.getNumberOfSheets();
int numbeoOfSheetsFile2 = xlsxWB.getNumberOfSheets();
for (int sheetIndex = 0; sheetIndex < numbeoOfSheetsFile1 && sheetIndex < numbeoOfSheetsFile2; sheetIndex++) {
HSSFSheet sheetFile1 = xlsWB.getSheetAt(sheetIndex);
XSSFSheet sheetFile2 = xlsxWB.getSheetAt(sheetIndex);
int noOfRowsSheetFile1 = sheetFile1.getLastRowNum();
int noOfRowsSheetFile2 = sheetFile2.getLastRowNum();
if (noOfRowsSheetFile1 < noOfRowsSheetFile2) {
for (int vRow = noOfRowsSheetFile1; vRow <= noOfRowsSheetFile2 - 1; vRow++) {
sheetFile2.createRow(vRow).setRowStyle(xlsxStyle);
//sheetFile2.getRow(vRow).setRowStyle(xlsxStyle);
}
}
if (noOfRowsSheetFile1 > noOfRowsSheetFile2) {
for (int vRow = noOfRowsSheetFile2 + 1; vRow <= noOfRowsSheetFile1; vRow++) {
sheetFile2.createRow(vRow).setRowStyle(xlsxStyle);
//sheetFile2.getRow(vRow).setRowStyle(xlsxStyle);
}
}
for (int vRow = 0; vRow <= noOfRowsSheetFile1; vRow++) {
HSSFRow rwFile1 = sheetFile1.getRow(vRow);
XSSFRow rwFile2 = sheetFile2.getRow(vRow);
int noOfColSheetFile1 = sheetFile1.getRow(vRow).getLastCellNum();
int noOfColSheetFile2 = 0;
try {
noOfColSheetFile2 = sheetFile2.getRow(vRow).getLastCellNum();
} catch (NullPointerException e) {
rwFile2 = sheetFile2.createRow(vRow);
noOfColSheetFile2 = 0;
}
// Coloring of mismatch columns
if (noOfColSheetFile1 < noOfColSheetFile2) {
for (int vCol = noOfColSheetFile1 + 1; vCol <= noOfColSheetFile2; vCol++) {
rwFile2.createCell(vCol);
//rwFile2.getCell(vCol).setCellStyle(xlsxStyle);
}
}
if (noOfColSheetFile1 > noOfColSheetFile2) {
for (int vCo2 = noOfColSheetFile2 + 1; vCo2 <= noOfColSheetFile1; vCo2++) {
rwFile2.createCell(vCo2);
//rwFile2.getCell(vCo2).setCellStyle(xlsxStyle);
}
}
for (int vCol = 0; vCol < noOfColSheetFile1; vCol++) {
//System.out.println("vCol>>" + vCol + "--vRow>>" + vRow);
HSSFCell cellFile1 = rwFile1.getCell(vCol);
XSSFCell cellFile2 = rwFile2.getCell(vCol);
String cellFile1Value = null;
if (null != cellFile1) {
cellFile1Value = cellFile1.toString();
}
String cellFile2Value = null;
if (null != cellFile2) {
cellFile2Value = cellFile2.toString();
}
if ((null == cellFile1Value && null != cellFile2Value) || (null != cellFile1Value && null == cellFile2Value) || (null != cellFile1Value && cellFile1Value.compareTo(cellFile2Value) != 0)) {
if ((null != cellFile1Value && !cellFile1Value.isEmpty()) || (null != cellFile2Value && ! cellFile2Value.isEmpty())) {
CellValues cellValues = new CellValues();
cellValues.setValue1(cellFile1Value);
cellValues.setValue2(cellFile2Value);
cellValues.setCellRow(vRow);
cellValues.setCellColumn(vCol);
scenarioResultDetails.addDifference(cellValues);
XSSFCell cellDiff = rwFile2.getCell(vCol);
if (null == cellDiff) {
cellDiff = rwFile2.createCell(vCol);
}
cellDiff.setCellStyle(xlsxStyle);
}
}
}
}
}
String fileDiff = file2.replace(".xls", "_diff.xls");
FileOutputStream fileOut = new FileOutputStream(fileDiff);
xlsxWB.write(fileOut);
if (null != fileOut) {
try {
fileOut.close();
} catch (Exception e) {
}
}
if (scenarioResultDetails.getDifferencesList().size() > 0) {
scenarioResultDetails.setResult(false);
scenarioResultDetails.setResultText("Not Matched");
scenarioResultDetails.setDiffExcel(fileDiff);
} else {
scenarioResultDetails.setResult(true);
scenarioResultDetails.setResultText("Matched");
}
return scenarioResultDetails;
}
public static void openFile(String fileName){
ReportGenerator.getDriver().get("file://"+fileName);
}
private static CellStyle getCellStyle(XSSFWorkbook xssfWorkbook){
CellStyle style = xssfWorkbook.createCellStyle();
Font font = xssfWorkbook.createFont();
font.setColor(IndexedColors.BLACK.getIndex());
style.setFont(font);
style.setFillForegroundColor(HSSFColor.YELLOW.index);
style.setFillBackgroundColor(HSSFColor.YELLOW.index);
style.setFillPattern(CellStyle.ALIGN_RIGHT);
return style;
}
}
This behavior is still (or again) present. I'm using version 2.4.1 of the NuGet NPOI package which apparently has a FontHeight property bugfix, but it also introduced this.
The problem is that the font size the font returned by xssfWorkbook.createFont(); is way small. You have to set it explicitly like so:
IFont font = excel.CreateFont();
font.FontHeightInPoints = 11;
Also I got similar errors when overwriting a file that was previously repaired. Make sure you write to a clean/new file every time you change your code so no previous corruptions get in the way.
Full example:
/// <summary>
/// Return style for header cells.
/// </summary>
/// <returns></returns>
private static ICellStyle GetHeaderStyle(this XSSFWorkbook excel)
{
IFont font = excel.CreateFont();
font.IsBold = true;
//Added this explicitly, initial font size is tiny
font.FontHeightInPoints = 11;
ICellStyle style = excel.CreateCellStyle();
style.FillForegroundColor = IndexedColors.Grey25Percent.Index;
style.FillPattern = FillPattern.SolidForeground;
style.FillBackgroundColor = IndexedColors.Grey25Percent.Index;
style.BorderBottom = style.BorderLeft = style.BorderRight = style.BorderTop = BorderStyle.Thin;
style.BottomBorderColor = style.LeftBorderColor = style.RightBorderColor = style.TopBorderColor = IndexedColors.Black.Index;
style.SetFont(font);
return style;
}
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!
I am working on the utility which dumps the excel sheet content to the database (postgres 9.2 in my case) , The application is working very smoothly when all the cells are filled but whenever i am trying to run my code on the excel sheet which is having empty cell it is giving me NULL POINTER EXCEPTION . Can any one help me......?
code.... snips ...
public ArrayList fillList(int colIndex, int id, List<Cell> cells,
String path) {
// OrderedMap errorMap=new LinkedMap();
String error = null;
ArrayList<String> errorList = new ArrayList<String>();
// errorList=null;
try {
FileInputStream fileIn = new FileInputStream(path);
POIFSFileSystem fs;
fs = new POIFSFileSystem(fileIn);
HSSFWorkbook filename = new HSSFWorkbook(fs);
Cell number = null;
HSSFSheet sheet = filename.getSheetAt(0);
Row firstRow = sheet.getRow(0);
int flag = 0;
String errorValue = null;
int columnNo = colIndex;
if (columnNo != -1) {
for (Row row : sheet) {
if (row.getRowNum() != 0) {
Cell c = row.getCell(columnNo);
// row.getCell(arg0, arg1)
// cells.add(c);
System.out.println(c.getCellType());
if (c.getCellType() == Cell.CELL_TYPE_STRING &&
(id == 2 || id == 3)) {
cells.add(c);
} else if (c.getCellType() == Cell.CELL_TYPE_NUMERIC
&& id == 1) {
String s = row.getCell(columnNo).toString();
double d = Double.parseDouble(s);
String mob = Double.toString(d);
Cell sc = row.createCell((short) 2);
String text = NumberToTextConverter.toText(c
.getNumericCellValue());
// System.out.println(text);
sc.setCellValue(text);
cells.add(sc);
// Date date=c.getDateCellValue();
} else if (c.getCellType() == Cell.CELL_TYPE_NUMERIC && id == 4) {
String s = row.getCell(columnNo).toString();
double d = HSSFDateUtil.getExcelDate(c
.getDateCellValue());
// String date = Double.toString(d);
Cell sc = row.createCell((short) 2);
String date = new SimpleDateFormat("dd-MM-yyyy")
.format(c.getDateCellValue());
// System.out.println(text);
sc.setCellValue(date);
cells.add(sc);
}
else if (c.getCellType() == Cell.CELL_TYPE_BLANK && id == 1 ) {
String s = row.getCell(columnNo).toString();
Cell sc = row.createCell((short)2);
sc.setCellValue("-");
cells.add(sc);
}
else {
switch (c.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
errorValue = Double.toString(c
.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
errorValue = c.getStringCellValue();
break;
}
errorList.add(c.getRowIndex() + "$" + columnNo
+ "$" + errorValue + "$" + id);
}
/*
* if (c == null || c.getCellType() ==
* Cell.CELL_TYPE_BLANK) { cells.add(c); } else {
*
* cells.add(c);
*
* }
*/
flag = 1;
}// if to skip 1st row
}
} else {
// System.out.println("could not find column " + columnWanted +
// " in first row of " + fileIn.toString());
}
return errorList;
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return errorList;
}
Without knowing how you test for null on the cell, then if it throws a NPE on a certain line you should be about to test for null.
if (c == null)
If this really doesn't work then of course you can always catch the NPE
try {
cellType = c.getCellType();
} catch (NullPointerException e) {
// oops Null
// do something else.
}
I am fetching data from a excel sheet containing more than 3000 lines. But I am getting an exception like java.lang.IllegalArgumentException: The supplied POIFSFileSystem contained neither a 'Workbook' entry, nor a 'WORKBOOK' entry. Is it really an excel file?
Below is mine code-
public ActionForward exportExtraExcel(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println("inside exportExtraExcel----------> ");
// String fileName=request.getParameter("filePath");
// System.out.println("fileName----qqqqqqqqqqqqqq---->"+fileName);
String fileName = "C:\\Users\\apanigrahi\\Desktop\\tt.xls";
Statement st = null;
ResultSet rs = null;
EmployeeDTO employeeDTO = new EmployeeDTO();
List cellDataList = new ArrayList();
try {
FileInputStream fileInputStream = new FileInputStream(fileName);
POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream);
HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);
HSSFSheet hssfSheet = workBook.getSheetAt(0);
int rows = hssfSheet.getLastRowNum() + 1;
int col = -1;
for (int i = 0; i < rows; i++) {
HSSFRow hssfRow = hssfSheet.getRow(i);
if (i == 0)
col = hssfRow.getLastCellNum();
List cellTempList = new ArrayList();
for (int j = 0; j < col; j++) {
HSSFCell hssfCell = hssfRow.getCell((short) j);
cellTempList.add(hssfCell);
}
cellDataList.add(cellTempList);
}
} catch (Exception e)
{
e.printStackTrace();
}
List<Integer> empIdArr = new ArrayList<Integer>();
List<Integer> userIdArr = new ArrayList<Integer>();
List<String> empFnameArr = new ArrayList<String>();
List<String> empLnameArr = new ArrayList<String>();
List<String> employeeIdArr = new ArrayList<String>();
List<String> date1 = new ArrayList<String>();
ArrayList<ArrayList> biometric_Data = getBiometricData(cellDataList);
ArrayList<String> date_biometric_Data = biometric_Data.get(0);
ArrayList<String> emp_code_biometric_Data = biometric_Data.get(1);
ArrayList<String> working_hours_biometric_Data = biometric_Data.get(2);
ArrayList<String> date_biometric_Data1 = new ArrayList<String>();
ArrayList<String> emp_code_biometric_Data1 =new ArrayList<String>();
ArrayList<String> working_hours_biometric_Data1 = new ArrayList<String>();
List<EmployeeDTO> extra_empLeaveSummaryReport = new ArrayList<EmployeeDTO>();
try {
connMgr = InitServlet.connMgr;
conn = connMgr.getConnection("access");
st = conn.createStatement();
for (int j = 0; j < emp_code_biometric_Data.size(); j++)
{
String qry = "select emp_id,user_id,emp_first_name,emp_last_name,employee_id from \"Employee\" where employee_id='"
+ emp_code_biometric_Data.get(j)
+ "' and is_deleted is null and emp_current_country ='1' order by employee_id";
rs = st.executeQuery(qry);
if(rs!=null){
while (rs.next()) {
int empId = rs.getInt(1);
empIdArr.add(empId);
userIdArr.add(rs.getInt(2));
empFnameArr.add(rs.getString(3));
empLnameArr.add(rs.getString(4));
employeeIdArr.add(rs.getString(5));
date_biometric_Data1.add(date_biometric_Data.get(j));
emp_code_biometric_Data1.add(emp_code_biometric_Data.get(j));
working_hours_biometric_Data1.add(working_hours_biometric_Data.get(j));
}
}
connMgr.freeConnection("access", conn);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception in exportExcelLeaveSummary");
} finally {
rs.close();
st.close();
connMgr.freeConnection("access", conn);
}
for (int i = 0; i < employeeIdArr.size(); i++)
{
double hours_worked = Double.parseDouble(working_hours_biometric_Data.get(i));
if (hours_worked < 9.00 && hours_worked > 0.0)
{
String day_status = "Halfday";
try {
System.out.println("Inside if loop Halfday");
UserManager userManager = new UserManagerImpl();
employeeDTO = userManager.getEmployeeLeaveDetails(userIdArr.get(i));
employeeDTO.setDate(date_biometric_Data1.get(i));
employeeDTO.setEmployeeId(employeeIdArr.get(i));
employeeDTO.setFirstName(empFnameArr.get(i));
employeeDTO.setLastName(empLnameArr.get(i));
employeeDTO.setWorking_hours(working_hours_biometric_Data1.get(i));
int totalLeaves = employeeDTO.getTotalLeaves();
employeeDTO.setTotalLeaves(totalLeaves);
int plToCredit = employeeDTO.getPlToCredit();
employeeDTO.setPlToCredit(plToCredit);
int slclToCredit = employeeDTO.getSlclToCredit();
employeeDTO.setSlclToCredit(slclToCredit);
int slclTotalBal = totalLeaves - plToCredit;
employeeDTO.setSlclTotalBal(slclTotalBal);
connMgr = InitServlet.connMgr;
conn = connMgr.getConnection("access");
st = conn.createStatement();
String qry = "";
qry = "Select * from \"Est_Employee_Leave_Application\" Where leave_approval_status='Approved' and '"+ ConvertDate.stringtoSQLDate(date_biometric_Data
.get(i))
+ "' between leave_application_from_date and leave_application_to_date And emp_id ='"
+ empIdArr.get(i) + "'";
rs = st.executeQuery(qry);
if (!(rs.equals(null))) {
employeeDTO.setDay_status(day_status);
extra_empLeaveSummaryReport.add(employeeDTO);
request.setAttribute("leaveSummary",extra_empLeaveSummaryReport);
}
} catch (Exception e) {
e.printStackTrace();
System.out
.println("Exception in leaveDetailsReport method");
} finally {
rs.close();
st.close();
connMgr.freeConnection("access", conn);
}
}
if (hours_worked == 0.0) {
String day_status = "LOP";
try {
System.out.println("Inside if loop LOP");
UserManager userManager = new UserManagerImpl();
employeeDTO = userManager.getEmployeeLeaveDetails(userIdArr.get(i));
employeeDTO.setDate(date_biometric_Data1.get(i));
employeeDTO.setEmployeeId(employeeIdArr.get(i));
employeeDTO.setFirstName(empFnameArr.get(i));
employeeDTO.setLastName(empLnameArr.get(i));
employeeDTO.setWorking_hours(working_hours_biometric_Data1.get(i));
int totalLeaves = employeeDTO.getTotalLeaves();
employeeDTO.setTotalLeaves(totalLeaves);
int plToCredit = employeeDTO.getPlToCredit();
employeeDTO.setPlToCredit(plToCredit);
int slclToCredit = employeeDTO.getSlclToCredit();
employeeDTO.setSlclToCredit(slclToCredit);
int slclTotalBal = totalLeaves - plToCredit;
employeeDTO.setSlclTotalBal(slclTotalBal);
connMgr = InitServlet.connMgr;
conn = connMgr.getConnection("access");
st = conn.createStatement();
String qry = "";
qry = "Select * from \"Est_Employee_Leave_Application\" Where '"
+ ConvertDate.stringtoSQLDate(date_biometric_Data
.get(i))
+ "' between leave_application_from_date and leave_application_to_date And emp_id ='"
+ empIdArr.get(i) + "'";
rs = st.executeQuery(qry);
if (!(rs.equals(null))) {
employeeDTO.setDay_status(day_status);
extra_empLeaveSummaryReport.add(employeeDTO);
request.setAttribute("leaveSummary",
extra_empLeaveSummaryReport);
}
} catch (Exception e) {
e.printStackTrace();
System.out
.println("Exception in leaveDetailsReport method");
} finally {
rs.close();
st.close();
connMgr.freeConnection("access", conn);
}
}
}
List<String> columnName = new ArrayList<String>();
columnName.add("Date");
columnName.add("Emp_Id");
columnName.add("Emp_First_Name");
columnName.add("Emp_Last_Name");
columnName.add("SL/CL_TotalBal");
columnName.add("PL_ToCredit");
columnName.add("Total_Leaves");
columnName.add("SL/CL_ToCredit");
columnName.add("Working_Hours");
columnName.add("Day_status");
request.setAttribute("columnNames", columnName);
return mapping.findForward("EXTRA_DETAILED_REPORT");
}
#SuppressWarnings("rawtypes")
public ArrayList<ArrayList> getBiometricData(List cellDataList)
{
EmployeeDTO employeeDTO = new EmployeeDTO();
ArrayList<String> date_Biometric = new ArrayList<String>();
ArrayList<String> emp_code_Biometric = new ArrayList<String>();
ArrayList<String> working_hours_Biometric = new ArrayList<String>();
ArrayList<ArrayList> biometric_All = new ArrayList<ArrayList>();
for (int i = 2; i < cellDataList.size(); i++)
{
List cellTempList = (List) cellDataList.get(i);
for (int j = 0; j < cellTempList.size(); j++)
{
if (j == 0)
{
HSSFCell hssfCell = (HSSFCell) cellTempList.get(0);
Date d1 = hssfCell.getDateCellValue();
SimpleDateFormat sdfAct = new SimpleDateFormat("dd-MMM-YYYY");
String d2 = new SimpleDateFormat("EEEE").format(d1);
String week_day1 = "Sunday";
String week_day2 = "Saturday";
if (week_day1.equals(d2) || week_day2.equals(d2)) {
j = 15;
}
else {
employeeDTO.setDate(sdfAct.format(d1).toString());
}
}
if (j == 1) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(1);
// blank = hssfCell.toString();
// if(blank == "")
// System.out.println("N/A");
// //else
// //System.out.println(blank);
}
if (j == 2) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(2);
String emp_code1 = hssfCell.toString();
String temp = emp_code1;
String non_emp1="10003";
String non_emp2="1001";
String non_emp3="1002";
String non_emp4="1111";
String non_emp5="237";
String non_emp6="002";
String non_emp7="023";
String non_emp8="511";
if(temp.length()>3){
temp = ""+ Integer.parseInt(temp);
}
if(temp.equals(non_emp1)||temp.equals(non_emp2)||temp.equals(non_emp3)||temp.equals(non_emp4)||temp.equals(non_emp5)||temp.equals(non_emp6)||temp.equals(non_emp7)||temp.equals(non_emp8))
{
j=15;
}
else{
String emp_code = "EST" +temp;
employeeDTO.setEmp_code(emp_code);
System.out.println(emp_code);
}
}
if (j == 3) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(3);
String emp_name = hssfCell.toString();
employeeDTO.setName(emp_name);
}
if (j == 4) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(4);
// System.out.println(card_num);
}
if (j == 5) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(5);
String shift_start = hssfCell.toString();
}
if (j == 6) {
String emp_in = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(6);
try {
emp_in = hssfCell.toString();
} catch (Exception e) {
emp_in = "";
}
if (emp_in == "" || emp_in.isEmpty() || emp_in == null) {
} else {
}
}
if (j == 7) {
String emp_out = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(7);
try {
emp_out = hssfCell.toString();
} catch (Exception e) {
}
if (emp_out == "" || emp_out.isEmpty() || emp_out == null) {
} else {
}
}
if (j == 8) {
String shift_end = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(8);
}
if (j == 9) {
String status = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(9);
status = hssfCell.toString();
String holiday_status="Hol";
if(status.equals(holiday_status))
{
j=15;
}
}
if (j == 10) {
String emp_late = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(10);
try {
emp_late = hssfCell.toString();
} catch (Exception e) {
emp_late = "";
}
if (emp_late == "" || emp_late.isEmpty()
|| emp_late == null) {
} else {
}
}
if (j == 11) {
String emp_early = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(11);
try {
emp_early = hssfCell.toString();
} catch (Exception e) {
emp_early = "";
}
if (emp_early == "" || emp_early.isEmpty()
|| emp_early == null) {
} else {
}
}
if (j == 12) {
String hours_worked = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(12);
try {
hours_worked = hssfCell.toString();
employeeDTO.setHours_worked(hours_worked);
} catch (Exception e) {
hours_worked = "";
}
if (hours_worked == "" || hours_worked.isEmpty()|| hours_worked == null)
{
hours_worked = "0.00";
employeeDTO.setHours_worked(hours_worked);
}
date_Biometric.add(employeeDTO.getDate());
emp_code_Biometric.add(employeeDTO.getEmp_code());
working_hours_Biometric.add(employeeDTO.getHours_worked());
}
if (j == 13) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(13);
}
if (j == 14) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(14);
}
}
}
biometric_All.add(date_Biometric);
biometric_All.add(emp_code_Biometric);
biometric_All.add(working_hours_Biometric);
return biometric_All;
}
..................
In the above code I am geting the above mentioned exception in line
HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);