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
I am doing Bulk Upload Task in Alfresco.
Before this i created custom action to call java code, i also successfully read data from excel sheet, and i found node reference of target document as well as source Document. Using that node reference i am also able to create new multiple Documents.
Now My requirement is, I want to replace Excel Data in that newly created Document. I tried to replace it, But It replacing the String only in First line of document, and it also deleting Rest of the existing contents inside newly created document. I have written Below code for this.
In below code i am first simply trying to replace some hard coded data to the Document.
But My requirement is i want to replace the data inside document which i already read from excel file.
Java Code:
public class MoveReplacedActionExecuter extends ActionExecuterAbstractBase {
InputStream is;
Cell cell = null;
public static final String NAME = "move-replaced";
private FileFolderService fileFolderService;
private NodeService nodeService;
private ContentService contentService;
private SearchService searchService;
#Override
protected void addParameterDefinitions(List < ParameterDefinition > paramList) {
}
public void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {
try {
ContentReader contentReader = contentService.getReader(actionedUponNodeRef, ContentModel.PROP_CONTENT);
is = contentReader.getContentInputStream();
} catch (NullPointerException ne) {
System.out.println("Null Pointer Exception" + ne);
}
try {
Workbook workbook = new XSSFWorkbook(is);
Sheet firstSheet = workbook.getSheetAt(0);
Iterator < Row > iterator = firstSheet.rowIterator();
while (iterator.hasNext()) {
ArrayList < String > al = new ArrayList < > ();
System.out.println("");
Row nextRow = iterator.next();
Iterator < Cell > cellIterator = nextRow.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print("\t" + cell.getStringCellValue());
al.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print("\t" + cell.getBooleanCellValue());
al.add(String.valueOf(cell.getBooleanCellValue()));
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print("\t" + cell.getNumericCellValue());
al.add(String.valueOf(cell.getNumericCellValue()));
break;
}
}
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
String query = "PATH:\"/app:company_home/cm:Dipak/cm:OfferLetterTemplate.doc\"";
SearchParameters sp = new SearchParameters();
StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
sp.addStore(storeRef);
sp.setLanguage(SearchService.LANGUAGE_LUCENE);
sp.setQuery(query);
ResultSet resultSet = searchService.query(sp);
System.out.println("Result Set" + resultSet.length());
NodeRef sourceNodeRef = null;
for (ResultSetRow row: resultSet) {
NodeRef currentNodeRef = row.getNodeRef();
sourceNodeRef = currentNodeRef;
System.out.println(currentNodeRef.toString());
}
NodeRef n = new NodeRef("workspace://SpacesStore/78342318-37b8-4b42-aadc-bb0ed5d413d9");
try {
org.alfresco.service.cmr.model.FileInfo fi = fileFolderService.copy(sourceNodeRef, n, "JustCreated" + Math.random() + ".doc");
NodeRef newNode = fi.getNodeRef();
QName TYPE_AUTHORTY = QName.createQName("sunpharma.hr.model", "hrdoctype");
nodeService.setType(newNode, TYPE_AUTHORTY);
ContentReader contentReader1 = contentService.getReader(newNode, ContentModel.PROP_CONTENT);
InputStream is2 = contentReader1.getContentInputStream();
POIFSFileSystem fs = new POIFSFileSystem(is2);
HWPFDocument doc = new HWPFDocument(fs);
doc = replaceText1(doc, "Company", "Datamatics");
ContentWriter writerDoc = contentService.getWriter(newNode, ContentModel.PROP_CONTENT, true);
writerDoc.putContent(doc.getDocumentText());
} catch (FileExistsException | FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static HWPFDocument replaceText1(HWPFDocument doc, String findText, String replaceText) {
System.out.println("In the method replacetext" + replaceText);
Range r1 = doc.getRange();
System.out.println("Range of Doc : " + r1);
for (int i = 0; i < r1.numSections(); ++i) {
Section s = r1.getSection(i);
for (int x = 0; x < s.numParagraphs(); x++) {
Paragraph p = s.getParagraph(x);
for (int z = 0; z < p.numCharacterRuns(); z++) {
CharacterRun run = p.getCharacterRun(z);
String text = run.text();
if (text.contains(findText)) {
run.replaceText(findText, replaceText);
} else {
System.out.println("NO text found");
}
}
}
}
return doc;
}
public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
public void setSearchService(SearchService searchService) {
this.searchService = searchService;
}
}
Its not possible to take direct file stream object in alfresco.
so i created one file at local drive, in background i performed all replacement operations. and after that i read all data using file input stream object. and later i used file that stream with node.
and it gave me my desired output. :)
I am using POI to read excel file and convert it to a two-dimensional array. Following is code section:
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class XlsxRead_2 {
public XlsxRead_2(){
getvalue_1();
}
public static void getvalue_1(){
XSSFRow row;
XSSFCell cell;
String [][] value =null;
double[][] nums =null;
try {
FileInputStream inputStream = new FileInputStream("TEST.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
//get sheet number
int sheetCn = workbook.getNumberOfSheets();
for(int cn = 0; cn < sheetCn; cn++){
//get 0th sheet data
XSSFSheet sheet = workbook.getSheetAt(cn);
//get number of rows from sheet
int rows = sheet.getPhysicalNumberOfRows();
//get number of cell from row
int cells = sheet.getRow(cn).getPhysicalNumberOfCells();
for (int r = 0; r < rows; r++) {
row = sheet.getRow(r); // bring row
if (row != null) {
for (int c = 0; c < cells; c++) {
cell = row.getCell(c);
value = new String[rows][cells];
nums= new double [rows][cells];
if (cell != null) {
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_FORMULA:
value [r][c]= cell.getCellFormula();
break;
case XSSFCell.CELL_TYPE_NUMERIC:
value [r][c]= "" + cell.getNumericCellValue();
break;
case XSSFCell.CELL_TYPE_STRING:
value [r][c]= "" + cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_BLANK:
value [r][c]= "[BLANK]";
break;
case XSSFCell.CELL_TYPE_ERROR:
value [r][c]= "" + cell.getErrorCellValue();
break;
default:
}
System.out.print(value);
} else {
System.out.print("[null]\t");
}
} // for(c)
System.out.print("\n");
}
} // for(r)
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class Starter {
public static void main(String[] args) {
XlsxRead_2 gv=new XlsxRead_2();
}
}
However, it didn't work properly. Attached is wrong result in JAVA. When i worked it without using array, it work properly. Any suggestions is appreciated.
Result in java:
[[Ljava.lang.String;#167fdd33[[Ljava.lang.String;#1e965684
[[Ljava.lang.String;#4d95d2a2[[Ljava.lang.String;#53f65459
[[Ljava.lang.String;#3b088d51[[Ljava.lang.String;#1786dec2
[[Ljava.lang.String;#74650e52[[Ljava.lang.String;#15d0c81b
[[Ljava.lang.String;#6acdbdf5[[Ljava.lang.String;#4b1c1ea0
[[Ljava.lang.String;#3712b94[[Ljava.lang.String;#2833cc44
[[Ljava.lang.String;#33f88ab[[Ljava.lang.String;#27a8c74e
You should create array after first for loop. And also you should create values array for each sheet. And one more point you should print value[r][c] not value
I hope that helps you.
public class XlsxRead_2 {
public static void main(String[] args) {
XlsxRead_2 xread2 = new XlsxRead_2();
}
public XlsxRead_2() {
getvalue_1();
}
public static void getvalue_1() {
XSSFRow row;
XSSFCell cell;
String[][] value = null;
double[][] nums = null;
try {
FileInputStream inputStream = new FileInputStream("TEST.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
// get sheet number
int sheetCn = workbook.getNumberOfSheets();
for (int cn = 0; cn < sheetCn; cn++) {
// get 0th sheet data
XSSFSheet sheet = workbook.getSheetAt(cn);
// get number of rows from sheet
int rows = sheet.getPhysicalNumberOfRows();
// get number of cell from row
int cells = sheet.getRow(cn).getPhysicalNumberOfCells();
value = new String[rows][cells];
for (int r = 0; r < rows; r++) {
row = sheet.getRow(r); // bring row
if (row != null) {
for (int c = 0; c < cells; c++) {
cell = row.getCell(c);
nums = new double[rows][cells];
if (cell != null) {
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_FORMULA:
value[r][c] = cell.getCellFormula();
break;
case XSSFCell.CELL_TYPE_NUMERIC:
value[r][c] = ""
+ cell.getNumericCellValue();
break;
case XSSFCell.CELL_TYPE_STRING:
value[r][c] = ""
+ cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_BLANK:
value[r][c] = "[BLANK]";
break;
case XSSFCell.CELL_TYPE_ERROR:
value[r][c] = ""+cell.getErrorCellValue();
break;
default:
}
System.out.print(value[r][c]);
} else {
System.out.print("[null]\t");
}
} // for(c)
System.out.print("\n");
}
} // for(r)
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
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.
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");