How to add a new sheet into an existing xls file - java

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");

Related

how to write array object content in excel through selenium

int col = driver.findElements(By.xpath("//table[#id=\"transactionListData\"]/thead/tr/th")).size();
int row =driver.findElements(By.xpath("//table[#id=\"transactionListData\"]/tbody/tr")).size();
//ArrayList<Object[]> mydata = new ArrayList<Object[]>();
Object [][] ob = new Object[row][col];
for( int i=1; i<=row; i++)
{
for (int j=1; j<=col; j++)
{
String text =driver.findElement(By.xpath("//*[#id='transactionListData']/tbody/tr["+i+"]/td["+j+"]")).getText();
//System.out.println("text " +text);
ob[i][j] = text;
}
}
try {
String s = util.writeIntoExcel(ob, row, col);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//return flag;
}
I have passed ob in below function to write its content in to excel file. but unable to print where ob is a object array Object [][] ob = new Object[row][col];. I am getting an error where i am trying to write data in to excel regarding Object in to string conversion.
public static String writeIntoExcel(Object ob, int rowi,int colj ) throws IOException
{
int rowcount = rowi;
int colcount = colj;
Object oa[][] = new Object[rowcount][colcount];
oa = (Object[][]) ob;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Transacton History");
for (int i=1; i<=rowcount ; i++)
{
for (int j=1; j<=colcount ; j++)
{
String val = (String) oa[i][j];
Row row = sheet.createRow(i);
row.createCell(colj).setCellValue(val);
}
}
FileOutputStream fileOut = new FileOutputStream("\"\\\\btfin.com\\filesrv\\User\\Offshore\\SG1\\L097117\\user\\My Documents\\workbook.xlsx");
workbook.write(fileOut);
fileOut.close();
return "Data is written";
}
}
Answer to question above is :
Object [][] ob = new Object[row][col];
for( int i=1; i<=row; i++)
{
for (int j=1; j<=col; j++)
{
String text =driver.findElement(By.xpath("//*[#id='transactionListData']/tbody/tr["+i+"]/td["+j+"]")).getText();
//System.out.println("text " +text);
ob[i-1][j-1] = text;
}
}
// rest everything is fine..
public static String writeIntoExcel(Object[][] sob ) throws IOException
{
//String oa[][] = sob;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Transacton History");
Object cellvalue = null;
for (int i=0; i<=sob.length ; i++)
{
Row row = sheet.createRow(i + 1);
for (int j=0; j<=sob[i].length ; j++)
{
Cell cell=row.createCell(j+1);
cellvalue = sob[i][j];
if (cellvalue instanceof String)
cell.setCellValue((String)(cellvalue));
else if (cellvalue instanceof Integer)
cell.setCellValue((Integer)cellvalue);
cell.setCellValue((String)cellvalue);
}
}
FileOutputStream fileOut = new FileOutputStream("");
workbook.write(fileOut);
fileOut.close();
workbook.close();
return "Data is written";

Embed files in java using POI-XSSF

I need to embed files
(.ppt(x), .doc(x), .jpg, .txt,...)
in excel (format xlsx) using Java Apache POI.
I have found an example to embed files in excel (format xls) using
POI-HSSF
(Embed files into Excel using Apache POI),
but this example does not work with excel xlsx format.
Does somebody know if it is possible to do this using POI-XSSF ?
'try this it works for me...' use this jars to run this code.....
1) poi-3.13-20150929.jar
2) poi-ooxml-3.13-20150929.jar
3) poi-ooxml-schemas-3.13-20150929.jar
public String getReport() throws RecordNotFoundException{
ResultSet rs = null;
ResultSet rs1 = null;
Connection conn = null;
CallableStatement cstm = null;
PreparedStatement pstmt = null;
try {
HttpServletRequest request;
HttpSession session;
request = (HttpServletRequest) ActionContext.getContext().get(
"com.opensymphony.xwork2.dispatcher.HttpServletRequest");
session = request.getSession();
conn = JndiConnection.getOracleConnection();
String sReportName = "";
ArrayList<String> mainData = new ArrayList<String>();
conn = JndiConnection.getOracleConnection();
cstm = conn.prepareCall("your procedure name");
cstm.setString(1, first parameter);
cstm.setString(2, second parameter);
cstm.registerOutParameter(3, OracleTypes.CURSOR);
cstm.execute();
rs1 = (ResultSet) cstm.getObject(3);
ResultSetMetaData rsmd = rs1.getMetaData();
String sColumnData="Sr.No";
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
sColumnData+="~~" + rsmd.getColumnName(i);
}
String headerString=sColumnData.replace("Sr.No~~", "");
mainData.add(headerString);
while (rs1.next()) {
System.out.println("data...............::" + rs1.getString(1));
String sData = "data";
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String column=rs1.getString(rsmd.getColumnName(i));
if (column == null) {
String finalData = "";
sData += "~~" + finalData;
} else {
sData += "~~" + rs1.getString(rsmd.getColumnName(i));
}
}
String bodyData=sData.replace("data~~", "");
mainData.add(bodyData);
System.out.println();
}
System.out.println("main data...............::" + mainData);
session.setAttribute("myReportData", mainData);
sReportName = genReport(mainData, title in file, "file path");
if (!"".equals(sReportName)) {
session.setAttribute("myReportDataExcelFile", sReportName);
}
setFileInputStream(new BufferedInputStream(new FileInputStream(sReportName)));
setFileName(new File(sReportName).getName());
} catch (SQLException se) {
throw new RecordNotFoundException(se);
} catch (NestableException ne) {
throw new RecordNotFoundException(ne);
} catch (Exception e) {
throw new RecordNotFoundException(e);
} finally {
try {
JndiConnection.freeConnections(cstm, conn, rs, rs1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return SUCCESS;
}"
'Above method will get the from database and put it into the list, now use bellow method
to write xls file with POI HSSF.'
private String genReport(ArrayList<String> arrDisplayDataList, String FileName, String sTitleName, String sPath)
throws Exception {
String fileNameWithPath;
Exception exception;
int col = 0;
int sno = 1;
fileNameWithPath = "";
String sFromate = "";
Connection con = null;
String ColumnDataList[] = null;
System.out.println("::::: Inside genReport() 2:::::");
try {
String[] arrColumnList = arrDisplayDataList.get(0).split("~~");
System.out.println("Length:::" + arrColumnList.length);
if (arrColumnList.length > 1) {
System.out.println("==Inside Of Record Data===");
DateFormat dateFormat = new SimpleDateFormat("ddMMyyyyHHmmss");
Calendar cal = Calendar.getInstance();
sFromate = dateFormat.format(cal.getTime());
FileName = (new StringBuilder()).append(FileName).append("_").append(sFromate).toString();
fileNameWithPath = (new StringBuilder()).append(sPath).append("/").append(FileName).append(".xls")
.toString();
File f1 = new File((new StringBuilder()).append(sPath).append("/").append(FileName).append(".xls")
.toString());
f1.getParentFile().mkdirs();
HSSFWorkbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream(f1);
HSSFSheet sheets = wb.createSheet("Sheet" + (sno++));
int row = 1;
HSSFRow rows;
if (row == 1) {
rows = sheets.createRow(0);
HSSFCell cells = rows.createCell(0);
cells.setCellType(1);
HSSFCellStyle cellStyle1 = wb.createCellStyle();
cellStyle1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle1.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle1.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cells.setCellStyle(cellStyle1);
cells.setCellValue(sTitleName);
HSSFCellStyle cellStyle = wb.createCellStyle();
HSSFFont fontStyle = wb.createFont();
cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
fontStyle.setColor(IndexedColors.BLACK.getIndex());
fontStyle.setBoldweight((short) 700);
fontStyle.setFontHeightInPoints((short) 12);
cellStyle.setFillPattern((short) 1);
cellStyle.setFont(fontStyle);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cells.setCellStyle(cellStyle);
sheets.addMergedRegion(new CellRangeAddress(0, 0, 0, arrColumnList.length - 1));
for (int columnIndex = 0; columnIndex < 50; columnIndex++) {
sheets.autoSizeColumn(columnIndex);
}
}
rows = sheets.createRow(row++);
for (col = 0; col < arrColumnList.length; col++) {
HSSFCell cells = rows.createCell(col);
String sVal = (String) arrColumnList[col];
cells.setCellType(1);
cells.setCellValue(sVal);
HSSFCellStyle cellStyle = wb.createCellStyle();
HSSFFont fontStyle = wb.createFont();
fontStyle.setColor(IndexedColors.BLACK.getIndex());
fontStyle.setBoldweight((short) 700);
fontStyle.setFontHeightInPoints((short) 10);
cellStyle.setFont(fontStyle);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cells.setCellStyle(cellStyle);
for (int columnIndex = 0; columnIndex < 100; columnIndex++) {
sheets.autoSizeColumn(columnIndex);
}
}
int rownum = 2;
int rowcount = 0;
for (int i = 1; i < arrDisplayDataList.size(); i++) {
if (rownum >= 65000) {
sheets = wb.createSheet("Sheet " + (sno++));
rownum = 0;
}
rows = sheets.createRow(rownum++);
String sData = ((String) arrDisplayDataList.get(i)).toString();
String sSplitData[] = sData.split("~~");
int xcount = 0;
for (col = 0; col < sSplitData.length; col++) {
HSSFCell cells = rows.createCell(xcount++);
String sVal = sSplitData[col];
if (sVal.equalsIgnoreCase("Total")) {
HSSFCellStyle cellStyle = wb.createCellStyle();
HSSFFont fontStyle = wb.createFont();
fontStyle.setColor(IndexedColors.BLACK.getIndex());
fontStyle.setBoldweight((short) 600);
fontStyle.setFontHeightInPoints((short) 12);
cellStyle.setFont(fontStyle);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
// cells.setCellStyle(cellStyle);
cells.setCellType(1);
for (int k = 3; k < rows.getLastCellNum(); k++) {// For
// each
// cell
// in
// the
// row
rows.getCell(k).setCellStyle(cellStyle);// Set
// the
// sty;e
}
cells.setCellValue(sVal);
System.out.println("TTT:" + sVal);
} else {
/*
* HSSFCellStyle cellStyle = wb.createCellStyle();
* cellStyle
* .setBorderBottom(HSSFCellStyle.BORDER_THIN);
* cellStyle
* .setBorderTop(HSSFCellStyle.BORDER_THIN);
* cellStyle
* .setBorderRight(HSSFCellStyle.BORDER_THIN);
* cellStyle
* .setBorderLeft(HSSFCellStyle.BORDER_THIN);
* //cells.setCellStyle(cellStyle);
* cells.setCellType(1);
*/
cells.setCellValue(sVal);
}
}
}
wb.write(fileOut);
fileOut.close();
} else {
fileNameWithPath = "NO RECORD FOUND";
}
} catch (Exception e) {
System.out.println("Exception ::::" + e);
e.printStackTrace();
throw e;
}
return fileNameWithPath;
}

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

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.

Create Multiple Sheet in jExcel API

I need to create multiple excel sheet in Java using jExcel API if one sheet is full (65536 rows). Suppose if one sheet got full then in the next sheet it should start writing automatically from where it left off in the first sheet. I am just stuck on putting the logic to create it dynamically whenever one sheet is full. Below is the code that I have done so far.
public void write() throws IOException, WriteException {
File file = new File(inputFile);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
writingToExcel(workbook);
}
//Logic to create sheet dyanmically if one is full should be done here I guess?
private void writingToExcel(WritableWorkbook workbook) {
workbook.createSheet("Report", 0);
WritableSheet excelSheet = workbook.getSheet(0);
try {
createLabel(excelSheet);
createContent(excelSheet);
} catch (WriteException e) {
e.printStackTrace();
} finally {
try {
workbook.write();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
private void createLabel(WritableSheet sheet) throws WriteException {
WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
times = new WritableCellFormat(times10pt);
times.setWrap(true);
WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false,UnderlineStyle.SINGLE);
timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
timesBoldUnderline.setWrap(true);
CellView cv = new CellView();
cv.setFormat(times);
cv.setFormat(timesBoldUnderline);
cv.setAutosize(true);
// Write a few headers
addCaption(sheet, 0, 0, "Header 1");
addCaption(sheet, 1, 0, "This is another header");
}
private void createContent(WritableSheet sheet) throws WriteException,
RowsExceededException {
for (int i = 1; i < 70000; i++) {
addNumber(sheet, 0, i, i + 10);
addNumber(sheet, 1, i, i * i);
}
}
private void addCaption(WritableSheet sheet, int column, int row, String s)
throws RowsExceededException, WriteException {
Label label;
label = new Label(column, row, s, timesBoldUnderline);
sheet.addCell(label);
}
private void addNumber(WritableSheet sheet, int column, int row,
Integer integer) throws WriteException, RowsExceededException {
Number number;
number = new Number(column, row, integer, times);
sheet.addCell(number);
}
I am not sure how to add that logic here in my code.
Any suggestions will be of great help?
Or in any case, can anyone provide me a simple example in which if one sheet is full, it should start writing automatically into different sheet (Second sheet)?
I made changes to the following 2 methods:-
private void writingToExcel(WritableWorkbook workbook) {
try {
// don't create a sheet now, instead, pass it in the workbook
createContent(workbook);
}
catch (WriteException e) {
e.printStackTrace();
}
finally {
try {
workbook.write();
workbook.close();
}
catch (IOException e) {
e.printStackTrace();
}
catch (WriteException e) {
e.printStackTrace();
}
}
}
// instead of taking a sheet, take a workbook because we cannot ensure if the sheet can fit all the content at this point
private void createContent(WritableWorkbook workbook) throws WriteException {
int excelSheetIndex = 0;
int rowIndex = 0;
WritableSheet excelSheet = null;
for (int i = 1; i < 70000; i++) {
// if the sheet has hit the cap, then create a new sheet, new label row and reset the row count
if (excelSheet == null || excelSheet.getRows() == 65536) {
excelSheet = workbook.createSheet("Report " + excelSheetIndex, excelSheetIndex++);
createLabel(excelSheet);
rowIndex = 0;
}
// instead of using i for row, use rowIndex
addNumber(excelSheet, 0, rowIndex, i + 10);
addNumber(excelSheet, 1, rowIndex, i * i);
// increment the sheet row
rowIndex++;
}
}
public class DscMigration {
private WritableCellFormat timesBoldUnderline;
private WritableCellFormat times;
private String inputFile;
public void setOutputFile(String inputFile) {
this.inputFile = inputFile;
}
public void write() throws IOException, WriteException {
File file = new File(inputFile);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
workbook.createSheet("Report", 0);
WritableSheet excelSheet = workbook.getSheet(0);
createLabel(excelSheet);
createContent(excelSheet);
workbook.write();
workbook.close();
}
private void createLabel(WritableSheet sheet) throws WriteException {
// Lets create a times font
WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
// Define the cell format
times = new WritableCellFormat(times10pt);
// Lets automatically wrap the cells
times.setWrap(true);
// Create create a bold font with unterlines
WritableFont times10ptBoldUnderline = new WritableFont(
WritableFont.TIMES, 10, WritableFont.BOLD, false,
UnderlineStyle.SINGLE);
timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
// Lets automatically wrap the cells
timesBoldUnderline.setWrap(true);
CellView cv = new CellView();
cv.setFormat(times);
// cv.setFormat(timesBoldUnderline);
// cv.setFormat(cf)
cv.setAutosize(true);
// Write a few headers
addCaption(sheet, 0, 0, "COM_ID");
addCaption(sheet, 1, 0, "OBJECTID");
addCaption(sheet, 2, 0, "GNOSISID");
}
private void createContent(WritableSheet sheet) throws WriteException,
RowsExceededException {
/**
* Create a new instance for cellDataList
*/
List<DataObj> cellDataListA = new ArrayList<DataObj>();
List<DataObj> nonDuplicateA = new ArrayList<DataObj>();
List<DataObj2> cellDataListB = new ArrayList<DataObj2>();
List<DataObj2> nonDuplicateB = new ArrayList<DataObj2>();
List<DataObj> nonDuplicateAB = new ArrayList<DataObj>();
List<DataObj> misMatchAB = new ArrayList<DataObj>();
List<DataObj> copyA = new ArrayList<DataObj>();
List<DataObj2> comID = new ArrayList<DataObj2>();
try {
/**
* Create a new instance for FileInputStream class
*/
// input1--> col1 -livelink id ; col2->livlink filename; col3-> gnosis id; col4-> filename
FileInputStream fileInputStream = new FileInputStream(
"C:/Documents and Settings/nithya/Desktop/DSC/Report/input1.xls");
//input2 --> col1 comid all, col2 -> object id for common
FileInputStream fileInputStream2 = new FileInputStream(
"C:/Documents and Settings/nithya/Desktop/DSC/Report/input2.xls");
/**
* Create a new instance for POIFSFileSystem class
*/
POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream);
POIFSFileSystem fsFileSystem2 = new POIFSFileSystem(fileInputStream2);
/*
* Create a new instance for HSSFWorkBook Class
*/
HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);
HSSFSheet hssfSheet = workBook.getSheetAt(0);
HSSFWorkbook workBook2 = new HSSFWorkbook(fsFileSystem2);
HSSFSheet hssfSheet2 = workBook2.getSheetAt(0);
/**
* Iterate the rows and cells of the spreadsheet to get all the
* datas.
*/
Iterator rowIterator = hssfSheet.rowIterator();
Iterator rowIterator2 = hssfSheet2.rowIterator();
while (rowIterator.hasNext()) {
HSSFRow hssfRow = (HSSFRow) rowIterator.next();
if ((hssfRow.getCell((short) 0) != null)
&& (hssfRow.getCell((short) 1) != null)) {
cellDataListA.add(new DataObj(hssfRow.getCell((short) 0)
.toString().trim(), hssfRow.getCell((short) 1)
.toString().trim()));
}
if ((hssfRow.getCell((short) 2) != null)
&& (hssfRow.getCell((short) 3) != null)) {
cellDataListB.add(new DataObj2(hssfRow.getCell((short) 2)
.toString().trim(), hssfRow.getCell((short) 3)
.toString().trim()));
}
}
// Replace Duplicate in Livelink Startd
Set set = new HashSet();
List newList = new ArrayList();
nonDuplicateA.addAll(cellDataListA);
for (int i = 0; i < nonDuplicateA.size(); i++) {
DataObj b = nonDuplicateA.get(i);
if (set.add(b.getCol1()))
newList.add(nonDuplicateA.get(i));
}
nonDuplicateA.clear();
nonDuplicateA.addAll(newList);
for (int i = 0; i < nonDuplicateA.size(); i++) {
DataObj a = nonDuplicateA.get(i);
}
System.out.println("nonDuplicateA=="+nonDuplicateA.size());
// Replace Duplicate in Livelink End
// Replace Duplicate in Gnosis Startd
Set set2 = new HashSet();
List newList2 = new ArrayList();
System.out.println("cellDataListB=="+cellDataListB.size());
nonDuplicateB.addAll(cellDataListB);
for (int i = 0; i < nonDuplicateB.size(); i++) {
DataObj2 b = nonDuplicateB.get(i);
if (set2.add(b.getCol1()))
newList2.add(nonDuplicateB.get(i));
}
nonDuplicateB.clear();
nonDuplicateB.addAll(newList2);
System.out.println("nonDuplicateB=="+nonDuplicateB.size());
// Replace Duplicate in Gnosis End
// Common record
//System.out.println("------Common----");
for (int i = 0; i < nonDuplicateA.size(); i++) {
DataObj a = nonDuplicateA.get(i);
for (int j = 0; j < nonDuplicateB.size(); j++) {
DataObj2 b = nonDuplicateB.get(j);
if((a.getCol2()!=null && b.getCol2()!=null )){
//System.out.println("---------");
if (a.getCol2().equalsIgnoreCase(b.getCol2())) {
// System.out.println(a.getCol2() +"--"+i+"--"+b.getCol2());
nonDuplicateAB.add(new DataObj(a.getCol1().toString()
.trim(), b.getCol1().toString().trim()));
//addLabel(sheet, 0, i, a.getCol1().toString().trim());
// addLabel(sheet, 1, i, b.getCol1().toString().trim());
break;
}
}
}
}
System.out.println("nonDuplicateAB=="+nonDuplicateAB.size());
TreeMap misA = new TreeMap();
//System.out.println("------Missing----");
for (int i = 0; i < nonDuplicateA.size(); i++) {
DataObj a = nonDuplicateA.get(i);
for (int j = 0; j < nonDuplicateB.size(); j++) {
DataObj2 b = nonDuplicateB.get(j);
if((a.getCol2()!=null && b.getCol2()!=null )){
if (!(a.getCol2().equals(b.getCol2()))) {
//System.out.println(a.getCol1() +"="+b.getCol1());
//break;
if(misA.containsValue(a.getCol2())){
misA.remove(a.getCol1());
}
else
{
misA.put(a.getCol1(), a.getCol2());
}
}
}
}
}
//System.out.println("SIze mis="+misA);
TreeMap misB = new TreeMap();
for (int i = 0; i < nonDuplicateB.size(); i++) {
DataObj2 a = nonDuplicateB.get(i);
for (int j = 0; j < nonDuplicateA.size(); j++) {
DataObj b = nonDuplicateA.get(j);
if((a.getCol2()!=null && b.getCol2()!=null )){
if (!(a.getCol2().equals(b.getCol2()))) {
//System.out.println(a.getCol1() +"="+b.getCol1());
if(misB.containsValue(a.getCol2())){
misB.remove(a.getCol1());
}
else
{
misB.put(a.getCol1(), a.getCol2());
}
}
}
}
}
// System.out.println("SIze misB="+misB);
//Getting ComID and Object Id from excel start
while (rowIterator2.hasNext()) {
HSSFRow hssfRow2 = (HSSFRow) rowIterator2.next();
if ((hssfRow2.getCell((short) 0) != null)
&& (hssfRow2.getCell((short) 1) != null)) {
comID.add(new DataObj2(hssfRow2.getCell((short) 0)
.toString().trim(), hssfRow2.getCell((short) 1)
.toString().trim()));
}
}
System.out.println("Size ComID="+comID.size());
TreeMap hm = new TreeMap();
System.out.println("Please wait...Data comparison.. ");
for (int i = 0; i < nonDuplicateAB.size(); i++) {
DataObj a = nonDuplicateAB.get(i);
for(int j=0;j<comID.size();j++ ){
DataObj2 b = comID.get(j);
//System.out.println((b.getCol2()+"---"+a.getCol1()));
if(b.getCol2().equalsIgnoreCase(a.getCol1())){
hm.put(b.getCol1(), b.getCol2());
break;
}
}
}
System.out.println("Size HM="+hm.size());
//Getting ComID and Object Id from excel End
//Data Base Updation
Connection conn = null;
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#cxxxxx:5487:dev", "",
"");
System.out.println("after calling conn");
Set set6 = hm.entrySet();
Iterator i = set6.iterator();
String gnosisNodeId="";
int update=1;
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
//System.out.print(me.getKey() + ": ");
//System.out.println(me.getValue());
// System.out.println("nonDuplicateAB="+nonDuplicateAB.size());
for(int m=0;m<nonDuplicateAB.size();m++){
DataObj a = nonDuplicateAB.get(m);
if(me.getValue().toString().equalsIgnoreCase(a.getCol1())){
gnosisNodeId=a.getCol2().toString();
nonDuplicateAB.remove(m);
break;
}
}
//System.out.println("nonDuplicateAB="+nonDuplicateAB.size());
if(gnosisNodeId!=null){
//System.out.println("LOOP");
String s1="UPDATE component SET com_xml = UPDATEXML(com_xml, '*/url/value/text()', '";
String s2="http://dmfwebtop65.pfizer.com/webtop/drl/objectId/"+gnosisNodeId;
String s3="') where com_id="+me.getKey().toString().substring(1)+"";
Statement stmt1=null;
//http://dmfwebtop65.pfizer.com/webtop/drl/objectId/0901201b8239cefb
try {
String updateString1 = s1+s2+s3;
stmt1 = conn.createStatement();
int rows =stmt1.executeUpdate(updateString1);
if (rows>0) {
addLabel(sheet, 0, update, me.getKey().toString().substring(1));
addLabel(sheet, 1, update, me.getValue().toString().substring(1));
addLabel(sheet, 2, update,gnosisNodeId );
update++;
System.out.println("Update Success="+me.getKey().toString().substring(1)+ "-->" +me.getValue().toString().substring(1));
}
else
{
System.out.println("Not Updated="+me.getKey().toString().substring(1)+ "-->" +me.getValue().toString().substring(1));
}
} catch (SQLException e) {
System.out.println("No Connect" + e);
} catch (Exception e) {
System.out.println("Error "+e.getMessage());
}
}
else{System.out.println("No gnosis id found for ObjectID="+me.getKey().toString().substring(1)); }
}//While
} //try
catch (Exception e) {
e.printStackTrace();
}
}//Main try
catch (Exception e) {
e.printStackTrace();
}
} //method
private void addCaption(WritableSheet sheet, int column, int row, String s)
throws RowsExceededException, WriteException {
Label label;
label = new Label(column, row, s, timesBoldUnderline);
sheet.addCell(label);
}
private void addNumber(WritableSheet sheet, int column, int row,
Integer integer) throws WriteException, RowsExceededException {
Number number;
number = new Number(column, row, integer, times);
sheet.addCell(number);
}
private void addLabel(WritableSheet sheet, int column, int row, String s)
throws WriteException, RowsExceededException {
Label label;
label = new Label(column, row, s, times);
sheet.addCell(label);
}
public static void main(String[] args) throws WriteException, IOException {
DscMigration test = new DscMigration();
test.setOutputFile("C:/Documents and Settings/nithya/Desktop/DSC/Report/Mapping.xls");
test.write();
System.out
.println("Please check the result file under C:/Documents and Settings/nithya/Desktop/DSC/Report/Report.xls ");
}
}
XXXXInternal Use
Based on WTTE-0043 ELC Maintenance Release and Bug Fix Plan Template
Version 4.0 Effective Date: 01-Jul-2010
//Bug Fix Plan
Author:
1 Approval Signatures
Table of Contents
I have authored this deliverable to document the plan for executing a maintenance release or bug fix to project.
NAME DATE
I have authored this deliverable to document the plan for executing a maintenance release or bug fix to XXX Plus v4.5.
NAME DATE
I approve this change and agree that this record represents the accurate and complete plan for executing the maintenance release or bug fix, and fully supports the implementation, testing and release activities for this project.
NAME DATE
I have reviewed the content of this record and found that it meets the applicable BT compliance requirements.
NAME DATE
Signatures
2 Introduction
This project deliverable documents the requested change, planned approach, development solution, test plan, test results and release approval for a maintenance release or and bug fix to project.
3 Change Request
Requestor Name:
XX
Object/
System Name:
project
Priority (High/Medium/Low):
High
Change Request No.:
NA
Change Request Date:
22-NOV-2011
Description of Problem or Requested Change:
Estimated Development Time Needed:
1 day (approx.)
4)4 Maintenance Release and Bug Fix Approach
5 Development Solution
8 Supporting References
9 Revision History

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