I can successfully read Excel file (.xls) using Event model POI. I am not using the usermodel (org.apache.poi.ss.usermodel) but an Event API to process xls and xlsx files (to address the memory footprint issue). However, when reading an .xls file with multiple sheets, only first sheet is read. Other sheets are ignored.
I am implementing HSSFListener and overriding its processRecord(Record record) method for xls files.
Here is my part of the code:
/**
* Main HSSFListener method for xls. It processes events and creates a RuntimeRecord to put into the DataPool.
*/
public void processRecord(Record record) {
int thisRow = -1;
String thisStr = null;
switch (record.getSid()) {
case BoundSheetRecord.sid:
boundSheetRecords.add(record);
break;
case BOFRecord.sid:
BOFRecord br = (BOFRecord)record;
if(br.getType() == BOFRecord.TYPE_WORKSHEET) {
// Works by ordering the BSRs by the location of their BOFRecords, and then knowing that we
// process BOFRecords in byte offset order
if(orderedBSRs == null) {
orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
}
// Check the existence of sheets
if(sheetIndex == 0) {
for(int i=0;i<excelSheetList.length;i++) {
boolean found = false;
if(this.getExcelSheetSpecification().equals(MSExcelAdapter.USE_WORKSHEET_NAME)) {
for(BoundSheetRecord rec : orderedBSRs) {
int len = rec.getSheetname().length();
if(len > 31)
this.warning("processRecord()","The length of sheet: " + rec.getSheetname() + " has more than 31 characters. Please change the name of the sheet, save the file and try again.");
}
}
if(this.getExcelSheetSpecification().equals(MSExcelAdapter.USE_WORKSHEET_NUMBER)) {
int sheetNo = Integer.parseInt(excelSheetList[i]);
if(sheetNo > 0 && sheetNo <= orderedBSRs.length) {
found = true;
}
} else {
for(int j=0;j<orderedBSRs.length;j++) {
if(this.getExcelSheetSpecification().equals(MSExcelAdapter.USE_WORKSHEET_NAME)) {
String sheetName = ((BoundSheetRecord) boundSheetRecords.get(j)).getSheetname();
if(excelSheetList[i].equals(sheetName)) {
found = true;
break;
}
}
}
}
if(!found)
this.error("processRecord()","Sheet: " + excelSheetList[i] + " does not exist.");
}
}
readCurrentSheet = true;
sheetIndex++;
System.out.println(sheetIndex);
if(this.getExcelSheetSpecification().equals(MSExcelAdapter.USE_WORKSHEET_NAME)) {
String sheetName = ((BoundSheetRecord) boundSheetRecords.get(sheetIndex-1)).getSheetname();
if(!canRead(sheetName)) {
readCurrentSheet = false;
}
} else {
if(!canRead(sheetIndex + "")) {
readCurrentSheet = false;
}
}
}
break;
case SSTRecord.sid:
sstRecord = (SSTRecord) record;
break;
case BlankRecord.sid:
BlankRecord brec = (BlankRecord) record;
thisRow = brec.getRow();
thisStr = null;
values.add(thisStr);
columnCount++;
break;
case FormulaRecord.sid:
FormulaRecord frec = (FormulaRecord) record;
thisRow = frec.getRow();
if(Double.isNaN( frec.getValue() )) {
// Formula result is a string
// This is stored in the next record
outputNextStringRecord = true;
nextRow = frec.getRow();
} else {
thisStr = formatListener.formatNumberDateCell(frec);
}
break;
case StringRecord.sid:
if(outputNextStringRecord) {
// String for formula
StringRecord srec = (StringRecord)record;
thisStr = srec.getString();
thisRow = nextRow;
outputNextStringRecord = false;
}
break;
case LabelSSTRecord.sid:
if(readCurrentSheet) {
LabelSSTRecord lsrec = (LabelSSTRecord) record;
thisRow = lsrec.getRow() + 1;
if(rowNumberList.contains(thisRow + "") ||
(rowNumberList.contains(END_OF_ROWS) && thisRow >= secondLastRow)) {
if(sstRecord == null) {
thisStr = "(No SST Record, can't identify string)";
} else {
thisStr = sstRecord.getString(lsrec.getSSTIndex()).toString();
}
}
}
break;
case NumberRecord.sid:
if(readCurrentSheet) {
NumberRecord numrec = (NumberRecord) record;
thisRow = numrec.getRow() + 1;
if(rowNumberList.contains(thisRow + "") ||
(rowNumberList.contains(END_OF_ROWS) && thisRow >= secondLastRow)) {
// No need to format.
// thisStr = formatListener.formatNumberDateCell(numrec); // Format
thisStr = String.valueOf(numrec.getValue());
}
}
break;
default:
break;
}
// Handle missing column
if(record instanceof MissingCellDummyRecord) {
thisStr = "";
}
// If we got something to print out, do so
if(thisStr != null) {
values.add(thisStr);
columnCount++;
}
// Handle end of row
if(record instanceof LastCellOfRowDummyRecord) {
if(readCurrentSheet) {
int currentRow = ((LastCellOfRowDummyRecord) record).getRow() + 1;
if(rowsReadSet.add(String.valueOf(currentRow))) {
if(processTestData) {
try {
int dpSize = this.getOutputDP().getSize();
if(dpSize < 1000 &&
(rowNumberList.contains(currentRow + "") ||
(rowNumberList.contains(END_OF_ROWS) && currentRow >= secondLastRow))) {
for(int i=columnCount; i<this.getConfigRecord().size(); i++) {
values.add(null); // Add empty string for missing columns
}
RuntimeRecord resultRecord = this.createRuntimeRecord(values);
this.fireRecordCreatedEvent(resultRecord);
this.putNextRecord(resultRecord);
}
} catch (Exception e) {
this.error("processRecord()",e.getMessage());
this.fireRecordCreationFailedEvent(e.getMessage(), e.getMessage());
}
} else {
try {
if(rowNumberList.contains(currentRow + "") || (rowNumberList.contains(END_OF_ROWS) && currentRow >= secondLastRow)) {
for(int i=columnCount; i<this.getConfigRecord().size(); i++) {
values.add(null); // Add empty string for missing columns
}
RuntimeRecord resultRecord = this.createRuntimeRecord(values);
this.fireRecordCreatedEvent(resultRecord);
this.putNextRecord(resultRecord);
}
} catch (Exception e) {
this.error("processRecord()",e.getMessage());
this.fireRecordCreationFailedEvent(e.getMessage(), e.getMessage());
}
}
}
values.removeAllElements();
columnCount = 0;
}
}
}
Here is the method that registers the listener:
private void readxls() throws FileNotFoundException, IOException {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(this.getFileName()));
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
request.addListenerForAllRecords(formatListener);
rowsReadSet.clear();
factory.processWorkbookEvents(request, fs);
}
When I debugged by adding some breakpoints, I noticed that it actually adds the column values to my values Vector. However, following condition is never matched for second sheet.
if(record instanceof LastCellOfRowDummyRecord) {
...
}
How to get rid off this problem? I want to read all the sheets in Excel file (.xls). I am using Apache POI 3.11-20141221 with JDK7.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
I am working on automating some excel task and when running the program, I stumbled across an error that says this:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "org.apache.poi.xssf.usermodel.XSSFRow.getCell(int)" because the return value of "org.apache.poi.xssf.usermodel.XSSFSheet.getRow(int)" is null
at com.excel.auto.ExcelAuto.main(ExcelAuto.java:43)
Below is the code that I have typed so far:
public class ExcelAuto {
public static void main(String args[]) throws IOException {
// To get File Path
Scanner scannerFilePath = new Scanner(System.in);
System.out.println("Please Enter File Path: ");
String excelFilePath = scannerFilePath.nextLine();
FileInputStream inputStream = new FileInputStream(excelFilePath);
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
// To get Sheet Name
Scanner scannerSheet = new Scanner(System.in);
System.out.println("Please Enter Excel Sheet Name: ");
String excelSheetName = scannerSheet.nextLine();
XSSFSheet sheet = workbook.getSheet(excelSheetName);
// To set matching transactions to yellow background
CellStyle stylePerfectTrades = workbook.createCellStyle();
stylePerfectTrades.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
stylePerfectTrades.setFillPattern(FillPatternType.SOLID_FOREGROUND);
DataFormatter df = new DataFormatter();
for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
Cell cellTitleWPBO = sheet.getRow(i).getCell(9);
Cell cellAmountWPBO = sheet.getRow(i).getCell(10);
Cell cellCheckStatusWPBO = sheet.getRow(i).getCell(6);
for (int j = 0; j < sheet.getLastRowNum() + 1; j++) {
Cell cellDescriptionSaxo = sheet.getRow(j).getCell(2);
Cell cellNetChangeSaxo = sheet.getRow(j).getCell(3);
Cell cellCheckStatusSaxo = sheet.getRow(j).getCell(5);
if (df.formatCellValue(cellCheckStatusSaxo).contains("-")) {
if (df.formatCellValue(cellDescriptionSaxo).contains(df.formatCellValue(cellTitleWPBO))) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals");
break;
}
// Transaction with same title but not same amount.
else {//If cell has a different value as the one in the row below it
System.out.println("Not Equals lah");
}
} else if (df.formatCellValue(cellTitleWPBO).contains("Conversion")) {
if (df.formatCellValue(cellDescriptionSaxo).contains("DEPOSIT")) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals (Conversion Deposit)");
break;
} else {
System.out.println("Not Equals Amount(Conversion)");
}
} else if (df.formatCellValue(cellDescriptionSaxo).contains("WITHDRAWAL")) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals (Conversion Deposit)");
break;
} else {
System.out.println("Not Equals Amount(Conversion)");
}
} else {
System.out.println("Not Equals (Conversion)");
}
} else if (df.formatCellValue(cellTitleWPBO).contains("stamp duty")) {
if (df.formatCellValue(cellDescriptionSaxo).contains("WITHDRAWAL")) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals (stamp duty)");
break;
} else {
System.out.println("Not Equals Amount(stamp duty)");
}
} else {
System.out.println("Not Equals (stamp duty)");
}
} else if (df.formatCellValue(cellTitleWPBO).contains("Dividend")) {
if (df.formatCellValue(cellDescriptionSaxo).contains("Corporate Actions ")) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals (dividend)");
break;
} else {
System.out.println("Not Equals Amount (Dividend)");
}
} else {
System.out.println("Not Equals (Dividend)");
}
} else if (df.formatCellValue(cellTitleWPBO).contains("Withdrawal")) {
if (df.formatCellValue(cellDescriptionSaxo).contains("WITHDRAWAL")) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals (Withdrawal)");
break;
} else {
System.out.println("Not Equals Amount (Withdrawal)");
}
} else {
System.out.println("Not Equals (Withdrawal)");
}
}
} else {
System.out.println("Checked");
}
}
FileOutputStream outputStream = new FileOutputStream(excelFilePath);
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
System.out.println("Done");
}
}
}
Change code blocks like this:
Cell cellTitleWPBO = sheet.getRow(i).getCell(9);
Cell cellAmountWPBO = sheet.getRow(i).getCell(10);
Cell cellCheckStatusWPBO = sheet.getRow(i).getCell(6);
to Code like this:
XSSFRow row = sheet.getRow(i);
if (row != null) {
Cell cellTitleWPBO = row.getCell(9);
Cell cellAmountWPBO = row.getCell(10);
Cell cellCheckStatusWPBO = row.getCell(6);
}
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 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);
}
}
}
}
}
}
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.
}