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.
}
Related
Is there any built in function that can be used to easily compare two rows in an Excel file. I am using Apache POI.
try {
Workbook wb1 = WorkbookFactory.create(new File(file1Path));
Sheet sheet1 = wb1.getSheetAt(0);
Workbook wb2 = WorkbookFactory.create(new File(file2Path));
Sheet sheet2 = wb2.getSheetAt(0);
for (Row myrow : sheet1) {
if (myrow.getRowNum() == 0) {
// add entire row to a sheet for 'found in file 1 but not file 2' -> sheet 0
write(myrow, output_filename_path, dstSheetNumberInOutputFile);
continue;
}
// look for this key in the other sheet
for (Row otherRow : sheet2) {
if (rowsAreEqual(myrow, otherRow)) {
write(myrow, output_filename_path, dstSheetNumberInOutputFile);
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
So I have an if statement that has the function rowsAreEqual() needs to compare equality of the two rows. How can I make the rowsAreEqual() function?
I tried this but hasn't worked:
private static boolean rowsAreEqual(Row myrow, Row otherRow) {
int equalCount = 0;
System.out.println("last cell num: " + myrow.getLastCellNum());
for(int i=0; i < myrow.getLastCellNum(); i++){
if(myrow.getCell(i) == otherRow.getCell(i)){
equalCount++;
System.out.println("Cells are the same: " + myrow.getCell(i) + " && " + otherRow.getCell(i));
}
}
if(equalCount == myrow.getLastCellNum()){
return true;
}
return false;
}
I figured it out like this. I had to make an extra function called getCellContentsAsString() so that I could compare the cells correctly:
private static boolean rowsAreEqual(Row myrow, Row otherRow) {
int equalCount = 0;
System.out.println("last cell num: " + myrow.getLastCellNum());
for(int i=0; i < myrow.getLastCellNum(); i++){
System.out.println(myrow.getCell(i) + " is the cell content in file1");
System.out.println(otherRow.getCell(i) + " is the cell content in file2");
Cell c1 = myrow.getCell(i);
Cell c2 = otherRow.getCell(i);
String s1 = getCellContentAsString(c1);
String s2 = getCellContentAsString(c2);
if(s1.equals(s2)){
equalCount++;
System.out.println("Cells are the same: " + myrow.getCell(i) + " && " + otherRow.getCell(i));
}
}
if(equalCount == myrow.getLastCellNum()){
return true;
}
return false;
}
private static String getCellContentAsString(Cell cell) {
String data = null;
if(cell.getCellType()==CellType.STRING) {
data = cell.getStringCellValue();
}
else if(cell.getCellType()==CellType.NUMERIC) {
data = String.valueOf(cell.getNumericCellValue());
}
return data;
}
You could abstract to comparing a range of cells.
This would allow you comparing either rows or columns, or individual regions (e.g. A1:Z256) - a so called Range.
So the object to compare - to be equal in contents - is CellRange.
In Java the boolean equals() method of any object relies on their int hashCode() function. In a utility-class called RangeContentsUtils you could implement both:
public class RangeContentsUtils {
public static boolean contentsEquals(CellRange rangeA, CellRange rangeB) {
if (rangeA == null || rangeB == null) {
return false;
}
if (rangeA.size() != rangeB.size()) {
return false;
}
// alternative would be:
// return stringContentsOf(rangeA).hashCode() == stringContentsOf(rangeB).hashCode();
return contentsToString(rangeA).equals(contentsToString(rangeB));
}
public static String contentsToString(CellRange range) {
StringBuilder sb = new StringBuilder();
Iterator<Cell> cellIterator = range.iterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
sb.append(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
sb.append(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
sb.append(cell.getStringCellValue());
break;
}
sb.append("\0"); // use NUL char as cell-separator
}
return sb.toString();
}
}
Now your row-comparison could use this utility class.
See also:
Compare specific row or column of xls sheet using java and Apache POI
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 read a excel file from my application using java code. It read all field's in right order,but whenever it has blank cells it auto fill with previous cell record.Here is my code
ServletContext servletContext = session.getServletContext();
File reportFile = new File(servletContext.getRealPath(sTempFile));
FileInputStream fIS = new FileInputStream(reportFile);
POIFSFileSystem theFile = new POIFSFileSystem(fIS);
m_workBook = new HSSFWorkbook(theFile);
HSSFSheet theSheet = m_workBook.getSheetAt(0);
//Take the first Sheet
int col = 12;
theSheet.setAutobreaks(true);
int row = theSheet.getPhysicalNumberOfRows() + 1;
String data[][] = new String[col][row];
int rowCount = 1;
while (rowCount < theSheet.getLastRowNum() + 1) {
//Inserts all the rows except the first_row
HSSFRow theSICDataRow = theSheet.getRow(rowCount++);
row = rowCount - 1;
HSSFCell cPaidAmount = null;
if (theSICDataRow.getCell((short) 11) != null) {
cPaidAmount = theSICDataRow.getCell((short) 11);
if (cPaidAmount.getCellType()== HSSFCell.CELL_TYPE_NUMERIC) {
BigDecimal bd = new BigDecimal(cPaidAmount.getNumericCellValue());
if (bd.intValue() == 0) {
sPaidAmount = "0";
}
else {
sPaidAmount = String.valueOf(bd.setScale(2, BigDecimal.ROUND_HALF_EVEN));
}
}
else if (cPaidAmount.getCellType()== HSSFCell.CELL_TYPE_STRING) {
sPaidAmount = "" + cPaidAmount.getStringCellValue();
}
}
else if (theSICDataRow.getCell((short) 11) == null) {
sPaidAmount = "";
}
The output should be ...
Paid amount
1200
1200
1200
1200
1690
..
..
..
..
..
..
But it appears
Paid amount
1200
1200
1200
1200
1690
1690
1690
1690
1690
1690
..
The source and generated temp file is ok,but the output show in table is in wrong .Please give some solutions.
Finally I got my answer and want to share it , I did not handle blank cells in my code so the POIFSFileSystem auto fill the blank cells with its previous record .Here is my code
HSSFCell cPaidAmount = null;
if (theSICDataRow.getCell((short) 11) != null) {
cPaidAmount = theSICDataRow.getCell((short) 11);
if (cPaidAmount.getCellType()== HSSFCell.CELL_TYPE_NUMERIC) {
BigDecimal bd = new BigDecimal(cPaidAmount.getNumericCellValue());
if (bd.intValue() == 0) {
sPaidAmount = "0";
}
else {
sPaidAmount = String.valueOf(bd.setScale(2, BigDecimal.ROUND_HALF_EVEN));
}
}
else if (cPaidAmount.getCellType()== HSSFCell.CELL_TYPE_STRING) {
sPaidAmount = "" + cPaidAmount.getStringCellValue();
}
else if (cPaidAmount.getCellType()== HSSFCell.CELL_TYPE_BLANK) {
sPaidAmount = "0";
}
}
else if (theSICDataRow.getCell((short) 11) == null) {
sPaidAmount = "0";
}
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.
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);
}
}
}
}
}
}