XLSX excel (POI Java). No data appear on row and column - java

Here's my code:
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);
//XSSFRow row = s.createRow(0);
if (_h != null) {
XSSFCell hd = row.createCell(c);
hd.setCellValue(_h);
}
int r = 5;
for (Iterator iter = Cells.iterator(); iter.hasNext();) {
Object[] _o = (Object[]) iter.next();
XSSFRow rowData = s.createRow(r);
XSSFCell data = rowData.createCell(c);
if (CellDataType[c].equals("STRING")
|| CellDataType[c].equals("VARCHAR")) {
String _l = (String) _o[c];
if (_l != null) {
// Label label = new Label(c, r, (String) _o[c]);
//XSSFCell data = rowData.createCell(c);
data.setCellValue(_l);
}
} else if (CellDataType[c].equals("DOUBLE")) {
Double _D = (Double) _o[c];
if (_D != null) {
// Number number = new Number(c, r,
// _D.doubleValue());
// s.addCell(number);
//XSSFCell data = rowData.createCell(c);
data.setCellValue(_D);
}
} else if (CellDataType[c].equals("INTEGER")) {
Integer _I = (Integer) _o[c];
if (_I != null) {
// Number number = new Number(c, r,
// _I.doubleValue());
// s.addCell(number);
//XSSFCell data = rowData.createCell(c);
data.setCellValue(_I);
}
} else if (CellDataType[c].equals("DATE")) {
Date _aDate = (Date) _o[c];
if (_aDate != null) {
// DateTime dateCell = new DateTime(c, r, _aDate,
// dateFormat);
// s.addCell(dateCell);
//XSSFCell data = rowData.createCell(c);
data.setCellValue(_aDate);
}
} else if (CellDataType[c].equals("TIMESTAMP")) {
Timestamp _aTimestamp = (Timestamp) _o[c];
Date _aDate = Timestamp2Date(_aTimestamp);
if (_aDate != null) {
// DateTime dateCell = new DateTime(c, r, _aDate,
// dateFormat);
// s.addCell(dateCell);
//XSSFCell data = rowData.createCell(c);
data.setCellValue(_aDate);
}
}
The XLSX excel did not manage to capture some data. The first two column is empty but there's 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

When you are writing the cell content, for each cell iteration, you are creating new row, which actually removing your previous row, and so at the end, you are getting data on your last cell only. Following is your code.
for (Iterator iter = Cells.iterator(); iter.hasNext();) {
Object[] _o = (Object[]) iter.next();
XSSFRow rowData = s.createRow(r);
s.createRow(0).createCell(0).setCellValue(Title);
You need to call create row just once for each row before entering in this loop. Once the row is created you just need to create column, and that must be for each column of that row It should be like following.
XSSFRow rowData = s.createRow(r);
for (Iterator iter = Cells.iterator(); iter.hasNext();) {
Object[] _o = (Object[]) iter.next();
rowData..createCell(0).setCellValue(Title);
Please note it is my first reflection on your code, and I have not tried the same on my system. So just take it as a hint and correct the same wherever required and then check again.

Related

Apache POI - Excel Import, insert data from a new sheet into a column

I'm here to ask for help in my java project in Netbeans.
I'm using Apache POI to import/export excel data. To make you understand what is the problem in my application, I'm showing you a print of the debug.
In the print, you can see 2 sheets. The first header "aiai" and the data from that sheet.
My problem is: How do i insert the data from "aiai2" which is the second sheet from my excel file, in its proper place, below the header "aiai2"
On other words, I want to separate the sheets vertically.
Below, I will show my code:
Workbook wb;
public String Importar(File archivo, JTable tablaD) {
String answer = "Unable to import";
DefaultTableModel modeloT = new DefaultTableModel();
tablaD.setModel(modeloT);
tablaD.getModel();
tablaD.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
try {
wb = WorkbookFactory.create(new FileInputStream(archivo));
int nsheets = wb.getNumberOfSheets();
for (int i = 0; i < nsheets; i++) {
Sheet sheet = wb.getSheetAt(i);
Iterator filaIterator = sheet.rowIterator();
int rownum = -1;
while (filaIterator.hasNext()) {
rownum++;
Row fila = (Row) filaIterator.next();
/*if (i > 0) {//se o nr da ficha atual for maior que 0, começa a escrever as linhas apartir da row 0 da tabela
modeloT.moveRow(modeloT.getRowCount() -1, modeloT.getRowCount() - 1, 0);
}*/
Iterator columnaIterator = fila.cellIterator();
Object[] listaColumna = new Object[1000];
int columnnum = -1;
while (columnaIterator.hasNext()) {
columnnum++;
Cell celda = (Cell) columnaIterator.next();
if (rownum == 0) {
modeloT.addColumn(celda.getStringCellValue());
} else {
if (celda != null) {
switch (celda.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
listaColumna[columnnum] = (int) Math.round(celda.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
listaColumna[columnnum] = celda.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
listaColumna[columnnum] = celda.getBooleanCellValue();
break;
default:
listaColumna[columnnum] = celda.getDateCellValue();
break;
}//end switch case
System.out.println("Column:" + columnnum + " Row:" + rownum + " value:" + celda + ".");
}
}
}//end while column Iterator
if (rownum != 0) {
modeloT.addRow(listaColumna);
}
}//end while row iterator
}//end for
answer = "Imported with success";
} catch (IOException | InvalidFormatException | EncryptedDocumentException e) {
System.err.println(e.getMessage());
}
return answer;
}
public String Exportar(File archivo, JTable tablaD) {
String answer = "Unable to export";
int numFila = tablaD.getRowCount(), numColumna = tablaD.getColumnCount();
if (archivo.getName().endsWith("xls")) {
wb = new HSSFWorkbook();
} else {
wb = new XSSFWorkbook();
}
Sheet hoja = wb.createSheet("Default");
try {
for (int i = -1; i < numFila; i++) {
Row fila = hoja.createRow(i + 1);
for (int j = 0; j < numColumna; j++) {
Cell celda = fila.createCell(j);
if (i == -1) {
celda.setCellValue(String.valueOf(tablaD.getColumnName(j)));
} else {
celda.setCellValue(String.valueOf(tablaD.getValueAt(i, j)));
}
wb.write(new FileOutputStream(archivo));
}
}
answer = "Exported with success";
} catch (Exception e) {
System.err.println(e.getMessage());
}
return answer;
}
As I understand your question, I assume you want to create a separate table for each sheet, one below other. In that case you need to create a new table everytime you read a new sheet. If you use only one table, you will get only one header.
Try this :
Create a new method Importar that takes a new table and a Sheet parameter
public String Importar(JTable tablaD, Sheet sheet) {
String answer = "Unable to import";
DefaultTableModel modeloT = new DefaultTableModel();
tablaD.setModel(modeloT);
tablaD.getModel();
tablaD.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
try {
Iterator filaIterator = sheet.rowIterator();
int rownum = -1;
....
....
So the calling method would be :
try {
Workbook wb = WorkbookFactory.create(new FileInputStream(archivo));
int nsheets = wb.getNumberOfSheets();
for (int i = 0; i < nsheets; i++) {
//You have to make sure your JTable gets rendered.
JTable tablaD = new JTable();
Importar( tablaD, wb.getSheetAt(i) );
}
} catch ( Exception e ) {
e.printStackTrace();
}
Important point is that your new table needs to get rendered or added to frame each time before you call Importar

in excel empty cells of non empty rows are neglected using java , POI jars

Excel To Json Conversion using JAVA, POI
Issue: Empty cells in Non Empty rows are neglected.
I am trying to convert an excel file through java to Json.A2 and B2 cells are empty but these cells are negleted i want even these cells to be counted and return an empty string
output obtained, the 2nd row starts from C2 by neglecting A2 and B2 which has empty values
public static String ExcelToJsonConverter(String filePath) throws Exception {
try {
FileInputStream inp = new FileInputStream(filePath);
Workbook workbook = WorkbookFactory.create(inp);
Sheet sheet = workbook.getSheetAt(0);
JSONArray rows = new JSONArray();
int coun = 0;
for (Iterator < Row > rowsIT = sheet.rowIterator(); rowsIT.hasNext();)
{
Row row = rowsIT.next();
JSONObject jRow = new JSONObject();
JSONArray cells = new JSONArray();
for (Iterator < Cell > cellsIT = row.cellIterator(); cellsIT.hasNext();) {
coun++;
Cell cell = cellsIT.next();
String val = "";
if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
System.out.println("Formula is " + cell.getCellFormula());
switch (cell.getCachedFormulaResultType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.println("Last evaluated as: " + cell.getNumericCellValue());
val = Double.toString(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
val = cell.getStringCellValue();
break;
}
} else if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
val = " ";
} else {
val = formatter.formatCellValue(cell);
}
enter code here
cells.put(val);
}
jRow.put("", cells);
rows.put(jRow);
}
json.put("", rows);
} catch (Exception e) {
//throw new BsfConstraintViolationException("Please Upload a valid file."+e.getMessage());
throw new BsfConstraintViolationException("Please Upload a valid file using Download Default BOQ option");
}
String formatJson = json.toString().replace("\"\":", "");
formatJson = formatJson.toString().replace("{", "");
formatJson = formatJson.toString().replace("}", "");
formatJson = formatJson.substring(1, formatJson.length() - 1);
return formatJson;
}
Advance Thanks to all

Passing multiple model in ModelAndView and Iterating those models

I have a requirement where I have to write HSSfWorkbook with multiple HSSfSheets.
For first sheet I have different columns and second sheet has different set of columns. For each sheet I have different stored procedure written.
Currently my java code is written in a way which can handle only one stored procedure data. I want to modify it and call second stored procedure to populate data in second sheet. I am setting the excel bean data in ModelAndView object and building the document. Now my question is how to fetch the each model and write it in HSSfSheet? Like in controller I am setting two beans in map downloadExcelBean and downloadExcelBean2. I want to write downloadExcelBean in first sheet and downloadExcelBean2 in second sheet. Please suggest.
My controller function is as below.
public ModelAndView exportToExcel(String fileName1, String filename2,String sheetname1,String sheetName2,
String[] headerLabels1, String[] headerLabels2,int[] datatypeArray1,int[] datatypeArray2, String procString1,String procString2,
Object[] objarray, HttpServletRequest arg0,
HttpServletResponse arg1, String[] dbColumnNameArray1,String[] dbColumnNameArray2)
throws Exception {
Log.info(DownloadExcelController.class,
"Execution Starts..exportExcel()");
Map<String, DownloadExcelBean> downloadExcelBean = new HashMap<String, DownloadExcelBean>();
//System.out.println(" in export excel part....."+procString+":::"+datatypeArray);
List<List> workLists1 = downloadExcelService.storedProcedureToExcel(
datatypeArray1, procString1, objarray, dbColumnNameArray1);
List<List> workLists2 = downloadExcelService.storedProcedureToExcel(
datatypeArray2, procString2, objarray, dbColumnNameArray2);
DownloadExcelBean bean = new DownloadExcelBean();
bean.setFilename(fileName1);
bean.setSheetname(sheetname1);
bean.setHeaderArray(headerLabels1);
bean.setDatatypeArray(datatypeArray1);
// bean.setVisibleArray(visibleArray);
bean.setData(workLists1);
DownloadExcelBean bean2 = new DownloadExcelBean();
bean2.setFilename(filename2);
bean2.setSheetname(sheetName2);
bean2.setHeaderArray(headerLabels2);
bean2.setDatatypeArray(datatypeArray2);
bean2.setData(workLists2);
downloadExcelBean.put("downloadExcelBean", bean);
downloadExcelBean.put("downloadExcelBean2", bean2);
return new ModelAndView("DownloadExcelView", "model",
downloadExcelBean);
}
And in DownloadExcelView.java I have build excel document function
protected void buildExcelDocument(Map model, HSSFWorkbook workbook,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
Log.info(DownloadExcelView.class,
"Execution starts....buildExcelDocument()");
response.setHeader("Content-Type", "application/vnd.ms-excel");
Map<String, DownloadExcelBean> exceldownload = (Map<String, DownloadExcelBean>) model.get("model");
for (Map.Entry<String, DownloadExcelBean> mapobject : exceldownload.entrySet())
{
DownloadExcelBean obj = (DownloadExcelBean) mapobject.getValue();
String filename = obj.getFilename(); // File name
String sheetname = obj.getSheetname(); // sheet Name
String headerlist[] = obj.getHeaderArray(); // header names
int dataTypeArray[] = obj.getDatatypeArray();
List resultsetValues = obj.getData();
response.setHeader("Content-Disposition", "attachment; filename="
+ filename + ".xls");
HSSFSheet sheet = workbook.createSheet(sheetname); // create a sheet
HSSFSheet sheet1 = workbook.createSheet("Second tab");
HSSFCellStyle cellStyle = setHeaderStyle(workbook); // Apply bold
// for header
HSSFRow header = sheet1.createRow(0); // create a header row
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
short decimalDataformat = workbook.createDataFormat().getFormat(
"#,###,##0.00");
HSSFCellStyle decimalCellStyle = workbook.createCellStyle();
decimalCellStyle.setDataFormat(decimalDataformat);
HSSFCellStyle wrapStyle = workbook.createCellStyle();
wrapStyle.setWrapText(true);
int visibleCol = -1;
for (int i = 0; i < headerlist.length; i++) {
visibleCol++;
HSSFCell cell = header.createCell(visibleCol);
cell.setCellStyle(cellStyle);
cell.setCellValue(headerlist[i].replace("<br/>", ARConstants.EXPORT_CRLF));
}
// Excel cell values
HSSFRow hssfrow;
HSSFCell cell;
for (int row = 0; row < resultsetValues.size(); row++) {
List rowList = (ArrayList) resultsetValues.get(row);
hssfrow = sheet1.createRow(row + 1);
visibleCol = -1;
for (int col = 0; col < rowList.size(); col++) {
// if(visibleArray[col]){
visibleCol++;
cell = hssfrow.createCell(visibleCol);
if (dataTypeArray[col] == java.sql.Types.DECIMAL) {
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellStyle(decimalCellStyle);
if (rowList.get(col) != null)
cell.setCellValue((Double) rowList.get(col));
else
cell.setCellValue("");
} else if (dataTypeArray[col] == java.sql.Types.DATE) {
if (rowList.get(col) != null)
cell.setCellValue(dateFormat.format(rowList
.get(col)));
else
cell.setCellValue("");
}
else if (dataTypeArray[col] == java.sql.Types.TIMESTAMP) {
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellStyle(wrapStyle);
if (rowList.get(col) != null)
cell.setCellValue(StringUtils.dateToUSFormatDateTimeTillMins(rowList.get(col).toString())
.replace(" ", ARConstants.EXPORT_CRLF));
else
cell.setCellValue("");
}
else if (dataTypeArray[col] == java.sql.Types.OTHER)
{
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellStyle(wrapStyle);
String crlf = Character.toString((char) 13)
+ Character.toString((char) 10);
if (rowList.get(col) != null)
{
String str=(rowList.get(col).toString()).replaceAll("\t"," ");
if((str.replace("|", crlf)).length()> 32767)
cell.setCellValue((str.replace("|", crlf)).substring(0,32766));
else
cell.setCellValue(str.replace("|", crlf));
}
else
cell.setCellValue("");
}
else
{
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
if (rowList.get(col) != null)
{
String str=(rowList.get(col).toString()).replaceAll("\t"," ");
if(str.length() > 32767)
{
cell.setCellValue(str.substring(0,32766));
}
else
{
cell.setCellValue(str);
}
}
else
cell.setCellValue("");
}
// sheet.autoSizeColumn(col);
}
}
}
Log.info(DownloadExcelView.class,
"Execution ends....buildExcelDocument()");
}

How to add a new sheet into an existing xls file

I need to add a new sheet with different methods and headers within the same workbook. I'm able to add the new sheet but how do add the separate methods and headers for the second sheet? Right now both sheets are duplicate copies. Basically How would I add different data to both sheets. Any help would be appreciated and I always accept the answers and also up vote.
public class ExcelWriter {
Logger log = Logger.getLogger(ExcelWriter.class.getName());
private HSSFWorkbook excel;
public ExcelWriter() {
excel = new HSSFWorkbook();
}
public HSSFWorkbook getWorkbook() {
return excel;
}
public void writeExcelFile(String filename, String[] columns, Object[][] data, HSSFCellStyle[] styles,
HSSFCellStyle columnsStyle, String[] header, String[] footer) throws IOException {
FileOutputStream out = new FileOutputStream(filename);
HSSFSheet sheet = excel.createSheet("Daily Screening");
HSSFSheet sheet1 = excel.createSheet("Parcel Return");
int numHeaderRows = header.length;
createHeader(sheet,header,columns.length, 0);
createHeader(sheet1,header,columns.length, 0);
createColumnHeaderRow(sheet,columns,numHeaderRows,columnsStyle);
createColumnHeaderRow(sheet1,columns,numHeaderRows,columnsStyle);
int rowCtr = numHeaderRows;
for( int i = 0; i < data.length; i++) {
if (i > data.length -2)
++rowCtr;
else
rowCtr = rowCtr + 2;
createRow(sheet, data[i], rowCtr, styles);
}
int rowCtr1 = numHeaderRows;
for( int i = 0; i < data.length; i++) {
if (i > data.length -2)
++rowCtr1;
else
rowCtr1 = rowCtr1 + 2;
createRow(sheet1, data[i], rowCtr1, styles);
}
int totalRows = rowCtr1 + 1;
createHeader(sheet1,footer,columns.length, totalRows);
excel.write(out);
out.close();
}
private void createHeader(HSSFSheet sheet1, String[] header, int columns, int rowNum) {
for( int i = 0; i < header.length ; i++ ) {
HSSFRow row = sheet1.createRow(i + rowNum);
HSSFCell cell = row.createCell((short) 0);
String text = header[i];
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(text);
HSSFCellStyle style = excel.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont arialBoldFont = excel.createFont();
arialBoldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
arialBoldFont.setFontName("Arial");
style.setFont(arialBoldFont);
if (!isEmpty(header[i]) && rowNum < 1) {
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
}
cell.setCellStyle(style);
sheet1.addMergedRegion( new Region(i+rowNum,(short)0,i+rowNum,(short)(columns-1)) );
}
}
private HSSFRow createColumnHeaderRow(HSSFSheet sheet, Object[] values, int rowNum, HSSFCellStyle style) {
HSSFCellStyle[] styles = new HSSFCellStyle[values.length];
for( int i = 0; i < values.length; i++ ) {
styles[i] = style;
}
return createRow(sheet,values,rowNum,styles);
}
private HSSFRow createRow(HSSFSheet sheet1, Object[] values, int rowNum, HSSFCellStyle[] styles) {
HSSFRow row = sheet1.createRow(rowNum);
for( int i = 0; i < values.length; i++ ) {
HSSFCell cell = row.createCell((short) i);
cell.setCellStyle(styles[i]);
try{
Object o = values[i];
if( o instanceof String ) {
String text = String.valueOf(o);
cell.setCellValue(text);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
}
else if (o instanceof Double) {
Double d = (Double) o;
cell.setCellValue(d.doubleValue());
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
}
else if (o instanceof Integer) {
Integer in = (Integer)o;
cell.setCellValue(in.intValue());
}
else if (o instanceof Long) {
Long l = (Long)o;
cell.setCellValue(l.longValue());
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
}
else if( o != null ) {
String text = String.valueOf(o);
cell.setCellValue(text);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
}
}
catch(Exception e) {
log.error(e.getMessage());
}
}
return row;
}
public boolean isEmpty(String str) {
if(str.equals(null) || str.equals(""))
return true;
else
return false;
}
}
Report Generator Class
public class SummaryReportGenerator extends ReportGenerator {
Logger log = Logger.getLogger(SummaryReportGenerator.class.getName());
public SummaryReportGenerator(String reportDir, String filename) {
super( reportDir + filename + ".xls", reportDir + filename + ".pdf");
}
public String[] getColumnNames() {
String[] columnNames = {"ISC\nCode", "Total\nParcels", "Total\nParcel Hit\n Count",
"Filter Hit\n%", "Unanalyzed\nCount", "Unanalyzed\n%",
"Name\nMatch\nCount", "Name\nMatch\n%", "Pended\nCount",
"Pended\n%", "E 1 Sanction\nCountries\nCount", "E 1 Sanction\nCountries\n%", "Greater\nthat\n$2500\nCount", "Greater\nthat\n$2500\n%",
"YTD\nTotal Hit\nCount", "YTD\nLong Term\nPending", "YTD\nLong Term\n%"};
return columnNames;
}
public HSSFCellStyle getColumnsStyle(HSSFWorkbook wrkbk) {
HSSFCellStyle style = wrkbk.createCellStyle();
style.setWrapText(true);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont timesBoldFont = wrkbk.createFont();
timesBoldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
timesBoldFont.setFontName("Times New Roman");
style.setFont(timesBoldFont);
return style;
}
public Object[][] getData(Map map) {
int rows = map.size();// + 1 + // 1 blank row 1; // 1 row for the grand total;
int cols = getColumnNames().length;
Object[][] data = new Object[rows][cols];
int row = 0;
for (int i=0; i < map.size(); i++ ){
try{
SummaryBean bean = (SummaryBean)map.get(new Integer(i));
data[row][0] = bean.getIscCode();
data[row][1] = new Long(bean.getTotalParcelCtr());
data[row][2] = new Integer(bean.getTotalFilterHitCtr());
data[row][3] = bean.getFilterHitPrctg();
data[row][4] = new Integer(bean.getPendedHitCtr());
data[row][5] = bean.getPendedHitPrctg();
data[row][6] = new Integer(bean.getTrueHitCtr());
data[row][7] = new Integer(bean.getRetiredHitCtr());
data[row][8] = new Integer(bean.getSanctCntryCtr());
data[row][9] = new Integer(bean.getC25Ctr());
data[row][10] = new Integer(bean.getCnmCtr());
data[row][11] = new Integer(bean.getCndCtr());
data[row][12] = new Integer(bean.getCnlCtr());
data[row][13] = new Integer(bean.getCneCtr());
data[row][14] = new Integer(bean.getVndCtr());
data[row][15] = new Integer(bean.getCilCtr());
data[row][16] = new Integer(bean.getHndCtr());
data[row][17] = new Integer(bean.getCnrCtr());
++row;
}
catch(Exception e) {
log.error(e.getMessage());
}
}
return data;
}
public String[] getHeader(String startDate, String endDate) {
Date today = new Date();
String reportDateFormat = Utils.formatDateTime(today, "MM/dd/yyyyHH.mm.ss");
String nowStr = Utils.now(reportDateFormat);
String[] header = {"","EXCS Daily Screening Summary Report ","",
"for transactions processed for the calendar date range",
"from " + startDate + " to " + endDate,
"Report created on " + nowStr.substring(0,10)+ " at "
+ nowStr.substring(10)};
return header;
}
public HSSFCellStyle[] getStyles(HSSFWorkbook wrkbk) {
int columnSize = getColumnNames().length;
HSSFCellStyle[] styles = new HSSFCellStyle[columnSize];
HSSFDataFormat format = wrkbk.createDataFormat();
for (int i=0; i < columnSize; i++){
styles[i] = wrkbk.createCellStyle();
if (i == 0){
styles[i].setAlignment(HSSFCellStyle.ALIGN_LEFT);
}else{
styles[i].setAlignment(HSSFCellStyle.ALIGN_RIGHT);
}
if (i == 1 || i == 2){
styles[i].setDataFormat(format.getFormat("#,###,##0"));
}
HSSFFont timesFont = wrkbk.createFont();
timesFont.setFontName("Times New Roman");
styles[i].setFont(timesFont);
}
return styles;
}
public String[] getFooter() {
String[] header = {"","Parcel Return Reason Code Reference","",
"DPM = Sender and/or recipient matches denied party",
"HND = Humanitarian exception not declared",
"CNM = Content not mailable under export laws",
"VND = Value of content not declared",
"CNR = Customer non-response",
"C25 = Content Value greater than $2500",
"CIL = Invalid license",
"C30 = More than one parcel in a calendar month",
"CNL = Content description not legible",
"CNE = Address on mailpiece not in English",
"RFN = Requires full sender and addressee names",
"DGS = Dangerous goods",
"R29 = RE-used 2976 or 2976A",
"ANE = PS Form 2976 or 2976A not in English",
"ICF = Incorrect Customs Declaration Form used",
"DPR = Declaration of purpose required",
"ITN = Internal Transaction Number (ITN), Export Exception/Exclusion Legend (ELL), or Proof of Filing Citation (PFC) is required",
"OTH = Other","",};
return header;
}
}
what you need is
HSSFSheet sheet = parentworkbookname.createSheet("Sample sheet2");

outOfMemoryError:java heap

public class seventhma {
XSSFSheet m_sheet;
int m_iNbRows;
int m_iCurrentRow = 0;
private static final String JAVA_TOSTRING = "EEE MMM dd HH:mm:ss zzz yyyy";
public seventhma(XSSFSheet sheet) {
m_sheet = sheet;
m_iNbRows = sheet.getPhysicalNumberOfRows();
}
/*
* Returns the contents of an Excel row in the form of a String array.
*
* #see com.ibm.ccd.common.parsing.Parser#splitLine()
*/
public String[] splitLine() throws Exception {
// if (m_iCurrentRow == m_iNbRows)
// return null;
XSSFRow row = m_sheet.getRow(m_iCurrentRow);
if (row == null) {
return null;
} else {
int cellIndex = 0;
int noOfCells = row.getPhysicalNumberOfCells();
String[] values = new String[noOfCells];
short firstCellNum = row.getFirstCellNum();
short lastCellNum = row.getLastCellNum();
if (firstCellNum >= 0 && lastCellNum >= 0) {
for (short iCurrent = firstCellNum; iCurrent < lastCellNum; iCurrent++) {
XSSFCell cell = (XSSFCell) row.getCell(iCurrent);
if (cell == null) {
values[iCurrent] = "";
cellIndex++;
continue;
} else {
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_NUMERIC:
double value = cell.getNumericCellValue();
if (DateUtil.isCellDateFormatted(cell))
{
if (DateUtil.isValidExcelDate(value)) {
Date date = DateUtil.getJavaDate(value);
SimpleDateFormat dateFormat = new SimpleDateFormat(JAVA_TOSTRING);
values[iCurrent] = dateFormat.format(date);
} else {
// throw new
// Exception("Invalid Date value found at row number "
// +
// row.getRowNum()+" and column number "+cell.getCellNum());
}
} else {
values[iCurrent] = value + "";
}
break;
case XSSFCell.CELL_TYPE_STRING:
values[iCurrent] = cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_BLANK:
values[iCurrent] = null;
break;
default:
values[iCurrent] = null;
}
}
}
}
m_iCurrentRow++;
return values;
}
}
public static void main(String args[]) {
XSSFWorkbook workBook = null;
File file = new File("E:\\Local\\Local2.xlsx");
InputStream excelDocumentStream = null;
try {
excelDocumentStream = new FileInputStream(file);
// POIFSFileSystem fsPOI = new POIFSFileSystem(new
// BufferedInputStream(excelDocumentStream));
BufferedInputStream bfs = new BufferedInputStream(excelDocumentStream);
workBook = new XSSFWorkbook(bfs);
seventhma parser = new seventhma(workBook.getSheetAt(0));
String[] res = null;
while ((res = parser.splitLine()) != null) {
for (int i = 0; i < res.length; i++) {
System.out.println("[" + res[i] + "]" + "\t");
}
System.out.println(res.length);
}
bfs = null;
excelDocumentStream.close();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
}
This program gives java heap out of space and when excel sheet containing 16 columns is uploaded it gives ArrayIndexOutOfBoundException.I had increased memory of eclipse upto -Xmx1600m but that also didnt work.
You get the ArrayIndexOutOfBoundException on the values array because you use the row.getPhysicalNumberOfCells() to determine its size. But row.getPhysicalNumberOfCells() will only count the cells that are actually filled in the file.
For example if you create an Excel sheet and only fill columns A, C and F and don't touch the other cells at all row.getPhysicalNumberOfCells() will return 3.
But you are iterating over all the cells by getting row.getFirstCellNum() and row.getLastCellNum(). So values[iCurrent] will sure be out of bounds once you reach cell F.
Regarding the OutOfMemory issue:
XSSF uses a LOT of memory. Try pushing your VM to as much memory as is possible for your machine. Or if you are just reading the files then try to go with the eventmodel API instead of the usermodel (think SAX vs. DOM).
(source: apache.org)

Categories