Loop on Class Members and write to Excel Apache POI - java

I have an array list of custom objects. I am trying to loop on these objects to write my output to an excel file.
In my code below, in the first loop, I set the header row in the excel file by looping over the class member variables. In the second loop, I write the object values.
My code:
class ChecklistOutput {
//Instantiating class data members
String a, b, c;
public ChecklistOutput() {
a = ""; b = ""; c = ""; }
}
private static ArrayList<ChecklistOutput> MasterOutput = new ArrayList<ChecklistOutput>();
private static void writeToMasterExcel() {
ChecklistOutput obj1 = new ChecklistOutput();
obj1.a = "AA"; obj1.b = "BB"; obj1.c = "CC";
ChecklistOutput obj1 = new ChecklistOutput();
obj2.a = "AA"; obj2.b = "BB"; obj2.c = "CC";
ChecklistOutput obj1 = new ChecklistOutput();
obj3.a = "AA"; obj3.b = "BB"; obj3.c = "CC";
ChecklistOutput obj1 = new ChecklistOutput();
obj4.a = "AA"; obj4.b = "BB"; obj4.c = "CC";
MasterOutput.add(obj1);
MasterOutput.add(obj2);
MasterOutput.add(obj3);
MasterOutput.add(obj4);
System.out.println(MasterOutput.size());
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = null;
HSSFRow row = null;
HSSFCell cell = null;
int rownum = 0, cellnum = 0;
sheet = workbook.createSheet("Master Spreadsheet");
row = sheet.createRow(rownum);
System.out.println("rownum " + rownum);
Class<?> c = new ChecklistOutput().getClass();
Field[] fields = c.getDeclaredFields();
// First loop
for (Field field : fields) {
cell = row.createCell(cellnum);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(field.getName());
cellnum += 1;
}
System.out.println(MasterOutput.size());
// Second loop
for (ChecklistOutput x : MasterOutput) {
// This prints 4 times meaning that there are 4 values in
// MasterOutput
System.out.println("Hell");
rownum += 1;
cellnum = 0;
row = sheet.createRow(rownum);
for (Field field : fields) {
cell = row.createCell(cellnum);
cell.setCellType(Cell.CELL_TYPE_STRING);
try {
// I can see values here
System.out.println(field.get(x).toString());
cell.setCellValue(field.get(x).toString());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
cellnum += 1;
}
}
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(new FileOutputStream(
"C:\\Users\\ABC\\Documents\\Checklist-Output.xls",
true));
workbook.write(bos);
bos.close();
workbook.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
However, I only get the header values in my excel file.
Output:
| a | b | c |
Can someone help me on this? Thanks!

Try this:
for (int col = 0; col < fields.length; col++) {
Field field = fields[col];
HSSFRow header = sheet.getRow(rownum);
if (header == null) {
header = sheet.createRow(rownum);
}
HSSFCell cell = header.createCell(col);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(field.getName());
}
for (ChecklistOutput x : MasterOutput) {
rownum += 1;
HSSFRow rowData = sheet.getRow(rownum);
if (rowData == null) {
rowData = sheet.createRow(rownum);
}
for (int col = 0; col < fields.length; col++) {
Field field = fields[col];
HSSFCell cellData = rowData.createCell(col);
cellData.setCellType(Cell.CELL_TYPE_STRING);
try {
// I can see values here
System.out.println(field.get(x).toString());
cellData.setCellValue(field.get(x).toString());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Also i recommend you use a POJO instead of ChecklistOutput (private fields with getters and setters).
I did the same thing you did. If you want the values for the fields from a pojo you can use reflection to invoke the getters. You can look into my question . It asks for something else, but provides a working example to get the values with reflection (i used it for POI as well).

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

Iterate vector element object

I am a newbie coder.
Can anyone teach me how to get the value inside storedVector1[3] ? I tried a lot of ways but i can only loop through storedVector and not the value inside the storedVector object
EDIT:
tableData.java
public class TableData {
static Vector storedVector = new Vector();
public void fillSortedData(File file, Vector data){
Workbook workbook = null;
Calendar now = Calendar.getInstance();
int monthnow = now.get(Calendar.MONTH) + 1;
try {
try {
workbook = Workbook.getWorkbook(file);
} catch (IOException ex) {
Logger.getLogger(
excelTojTable.class.getName()).log(Level.SEVERE, null, ex);
}
Sheet sheet = workbook.getSheet(0);
headers.clear();
for (int i = 0; i < sheet.getColumns(); i++) {
Cell cell1 = sheet.getCell(i, 0);
headers.add(cell1.getContents()); }
data.clear();
for (int j = 1; j < sheet.getRows(); j++) {
Vector d = new Vector();
for (int i = 0; i < sheet.getColumns(); i++) {
Cell cell = sheet.getCell(i, j);
d.add(cell.getContents());
CellType type = cell.getType();
if(type == CellType.DATE){
String cellDateStr = cell.getContents();
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
try {
Date cellDate = formatter.parse(cellDateStr);
int month = cellDate.getMonth() + 1;
if(monthnow != month) {
d.clear();
//d.removeAllElemen8ts();
i = sheet.getColumns();
}
} catch (ParseException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
if(d.isEmpty() == false) {
d.add("\n");
data.add(d);
storedVector.add(d);
}
}
} catch (BiffException e) {
e.printStackTrace();
}
}
public void emailList() {
int abc = storedVector.size();
//iterate through the vector and get all the element
}
}
}
I created a vector "data" using the same method as storedVector in another java class.
In tableData.java, I wanted to create a method "emaillist" that can iterate and get all the email that was show in the picture and save it in a list or array
Vector extends AbstractList. So it should have a Vector.get(i) method.
Try using
Vector v = storedVector.get(1);
Object o = v.get(3);
if storedVector is a list/set of Vector, this code can help:
for(Vector vector: storedVector){
for(int i=0; i< vector.size(); i++){
//access to vector[i]
}
}

Excel rows with multiple lines in one

I've created a Workbook to show an excel with different contents. That excel has some rows that contain some lines each. The problem is the excel only has that format when I click in a specific row and I want the entire excel looks like that.
This is my code:
Workbook worbook = new HSSFWorkbook();
Sheet sheet = worbook.createSheet("Publication List");
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Locale locale = resourceResponse.getLocale();
Font headerFont = worbook.createFont();
headerFont.setFontHeightInPoints((short) 11);
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
headerFont.setColor(new HSSFColor.DARK_BLUE().getIndex());
CellStyle headerStyle = worbook.createCellStyle();
headerStyle.setFont(headerFont);
headerStyle.setWrapText(true);
headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
headerStyle.setFillForegroundColor(new HSSFColor.GREY_25_PERCENT().getIndex());
try {
List < Country > countries = CountryServiceUtil.getCountries();
if (allRequests != null) {
int columnHeader = 0;
Row rowHead = sheet.createRow(0);
for (String headerColumn: header) {
Cell cell = rowHead.createCell(columnHeader);
cell.setCellValue(LanguageUtil.get(locale, headerColumn));
cell.setCellStyle(headerStyle);
columnHeader++;
}
int requestRow = 1;
for (PublicationRequest publication: allRequests) {
Row rowsBody = sheet.createRow(requestRow);
Country country = CountryServiceUtil.fetchCountryByA2(publication.getCountry());
String fullAddress = publication.getAddress() + StringPool.RETURN_NEW_LINE + publication.getCp() + StringPool.SPACE + publication.getCity() + StringPool.RETURN_NEW_LINE + country.getName();
rowsBody.createCell(8).setCellValue(fullAddress);
//Publication items. Cell 8
long scopeGroupId = PortalUtil.getScopeGroupId(resourceRequest);
List < PublicationRequestItem > allRequestItems = PublicationRequestItemLocalServiceUtil.findBypublicationRequestId(publication.getPublicationRequestId());
String publicationsVocabulary = PrefsParamUtil.getString(resourceRequest.getPreferences(), resourceRequest, "publicationsVocabulary", "");
AssetVocabulary publicationsTypeVocabulary = null;
if (Validator.isNotNull(publicationsVocabulary)) {
try {
publicationsTypeVocabulary = AssetVocabularyLocalServiceUtil.getAssetVocabularyByUuidAndGroupId(publicationsVocabulary, scopeGroupId);
String category = StringPool.BLANK;
for (PublicationRequestItem item: allRequestItems) {
JournalArticle latestArticle;
latestArticle = JournalArticleLocalServiceUtil.getLatestArticle(scopeGroupId, item.getArticleId());
if (!category.equals(StringPool.BLANK)) {
category = category + StringPool.NEW_LINE;
}
category += RequestDisplayUtil.getPublicationTitle(locale, latestArticle, publicationsTypeVocabulary);
}
rowsBody.createCell(9).setCellValue(category);
} catch (PortalException e) {
e.printStackTrace();
}
}
requestRow++;
}
for (int column = 0; column < columnHeader + 1; column++) {
sheet.autoSizeColumn(column);
}
}
} catch (SystemException e) {
_log.error("Error while creating Excel file", e);
} catch (PortalException e1) {
e1.printStackTrace();
}
resourceResponse.setContentType("application/vnd.ms-excel");
resourceResponse.setProperty("expires", "-1d");
resourceResponse.setProperty("Pragma", "no-cache");
resourceResponse.setProperty(HttpHeaders.CACHE_CONTROL, "no-cache");
I've tried as well with char(10) but I get the same end
Thank you
Finally I got a solution.
I only was giving styles to the header cells:
for (String headerColumn: header) {
Cell cell = rowHead.createCell(columnHeader);
cell.setCellValue(LanguageUtil.get(locale, headerColumn));
cell.setCellStyle(headerStyle);
columnHeader++;
I had to create the body cells previously and give it some style:
rowsBody.createCell(8).getCellStyle().setWrapText(true);
rowsBody.getCell(8).setCellValue(fullAddress);

Business Objects Java

I need help extracting all the file names within a folder in Business Objects. With the code I have now I can get the name of a single file within a folder. I want to get all the file names in that folder. The variable temp is where I enter the name of the file that I want. The variable doc is where the file name is retrieved, and the variable reportname is where I store doc to write to an external spreadsheet.
public class variable {
private static String expressionEx;
private static String nameEx;
private static String nameXE[] = new String[11];
private static String expressionXE[] = new String[11];
private static String query;
public static String reportName;
private static String reportPath;
/** This method writes data to new excel file * */
public static void writeDataToExcelFile(String fileName) {
String[][] excelData = preapreDataToWriteToExcel();// Creates first
// sheet in Excel
String[][] excelData1 = preapreDataToWriteToExcel1();// Creates
// second
// sheet in
// Excel
String[][] excelData2 = preapreDataToWriteToExcel2();// Creates third
// sheet in
// Excel
HSSFWorkbook myReports = new HSSFWorkbook();
HSSFSheet mySheet = myReports.createSheet("Variables");
HSSFSheet mySheet1 = myReports.createSheet("SQL Statement");
HSSFSheet mySheet2 = myReports.createSheet("File Info");
// edits first sheet
mySheet.setFitToPage(true);
mySheet.setHorizontallyCenter(true);
mySheet.setColumnWidth(0, 800 * 6);
mySheet.setColumnWidth(1, 7000 * 6);
// edits second sheet
mySheet1.setFitToPage(true);
mySheet1.setHorizontallyCenter(true);
mySheet1.setColumnWidth(0, 800 * 6);
mySheet1.setColumnWidth(1, 7000 * 6);
// edits third sheet
mySheet2.setFitToPage(true);
mySheet2.setHorizontallyCenter(true);
mySheet2.setColumnWidth(0, 800 * 6);
mySheet2.setColumnWidth(1, 2000 * 6);
HSSFRow myRow = null;
HSSFCell myCell = null;
// first sheet
for (int rowNum = 0; rowNum < excelData[0].length; rowNum++) {
myRow = mySheet.createRow(rowNum);
for (int cellNum = 0; cellNum < 4; cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(excelData[rowNum][cellNum]);
}
}
try {
FileOutputStream out = new FileOutputStream(fileName);
myReports.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
// second sheet
for (int rowNum = 0; rowNum < excelData1[0].length; rowNum++) {
myRow = mySheet1.createRow(rowNum);
for (int cellNum = 0; cellNum < 4; cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(excelData1[rowNum][cellNum]);
}
}
try {
FileOutputStream out = new FileOutputStream(fileName);
myReports.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
// third sheet
for (int rowNum = 0; rowNum < excelData2[0].length; rowNum++) {
myRow = mySheet2.createRow(rowNum);
for (int cellNum = 0; cellNum < 4; cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(excelData2[rowNum][cellNum]);
}
}
try {
FileOutputStream out = new FileOutputStream(fileName);
myReports.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* #param args
*/
public static String password;
public static String username;
public static String temp;
public variable() throws FileNotFoundException {
// TODO Auto-generated method stub
IEnterpriseSession oEnterpriseSession = null;
ReportEngines reportEngines = null;
try {
// String cmsname = "det0190bpmsdev3";
// String authenticationType = "secEnterprise";
String cmsname = "";
String authenticationType = "";
// Log in.
oEnterpriseSession = CrystalEnterprise.getSessionMgr().logon(
username, password, cmsname, authenticationType);
if (oEnterpriseSession == null) {
} else {
// Process Document
reportEngines = (ReportEngines) oEnterpriseSession
.getService("ReportEngines");
ReportEngine wiRepEngine = (ReportEngine) reportEngines
.getService(ReportEngines.ReportEngineType.WI_REPORT_ENGINE);
IInfoStore infoStore = (IInfoStore) oEnterpriseSession
.getService("InfoStore");
String query = "select SI_NAME, SI_ID from CI_INFOOBJECTS "
+ "where SI_KIND = 'Webi' and SI_INSTANCE=0 and SI_NAME ='"
+ temp + "'";
IInfoObjects infoObjects = (IInfoObjects) infoStore
.query(query);
for (Object object : infoObjects) {
IInfoObject infoObject = (IInfoObject) object;
String path = getInfoObjectPath(infoObject);
if (path.startsWith("/")) {
DocumentInstance widoc = wiRepEngine
.openDocument(infoObject.getID());
String doc = infoObject.getTitle();
reportPath = path;// this is the path of document
$$$$$$$$$ reportName = doc;// this is the document name
printDocumentVariables(widoc);
purgeQueries(widoc);
widoc.closeDocument();
}
}
// End processing
}
} catch (SDKException sdkEx) {
} finally {
if (reportEngines != null)
reportEngines.close();
if (oEnterpriseSession != null)
oEnterpriseSession.logoff();
}
}
public static void printDocumentVariables(DocumentInstance widoc) {
int i = 0;
// this is the report documents variables
ReportDictionary dic = widoc.getDictionary();
VariableExpression[] variables = dic.getVariables();
for (VariableExpression e : variables) {
nameEx = e.getFormulaLanguageID();
expressionEx = e.getFormula().getValue();
// stores variables in array
nameXE[i] = nameEx;
expressionXE[i] = expressionEx;
i++;
}
}
public static String getInfoObjectPath(IInfoObject infoObject)
throws SDKException {
String path = "";
while (infoObject.getParentID() != 0) {
infoObject = infoObject.getParent();
path = "/" + infoObject.getTitle() + path;
}
return path;
}
#SuppressWarnings("deprecation")
public static void purgeQueries(DocumentInstance widoc) {
DataProviders dps = widoc.getDataProviders();
for (int i = 0; i < dps.getCount(); ++i) {
DataProvider dp = (DataProvider) dps.getItem(i);
if (dp instanceof SQLDataProvider) {
SQLDataProvider sdp = (SQLDataProvider) dp;
sdp.purge(true);
query = sdp.getQuery().getSQL();
}
}
If Temp is going to hold the name of a unique folder, then you can use this code. Replace the String query = line with:
IInfoObjects oParents = infoStore.query("select si_id from ci_infoobjects where si_kind = 'folder' and si_name = '" + temp + "'");
if(oParents.size()==0)
return; // folder name not found
IInfoObject oParent = (IInfoObject)oParents.get(0);
String query = "select SI_NAME, SI_ID from CI_INFOOBJECTS "
+ "where SI_KIND = 'Webi' and si_parentid = " + oParent.getID();
I don't see in the code where you're populating the temp, username, or password variables, but I assume you just left that out of the listing intentionally. Obviously they will need to be defined.
Couple of other things I noticed in your code:
You are purging the query in each report, but not saving the report afterwards.
You are storing the report's SQL in an instance variable named query, but you also have a local variable named query in the variable constructor. This could very likely cause a conflict if you need the SQL value for something.
You have an "empty catch" for SDKException. SDKExceptions can happen for all kinds of reasons, and as it is you will not know why the program failed. You should at least be printing out the exception, or just let it bubble up.

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

Categories