Apache poi xlsx file with unsaved changes - java

I'am facing a wierd behaviours when creating excel spreadsheets with poi. I am able to save contents but when i open it on excel and try to close the document whitout touching it i get a messagebox with a message along the lines of "would you like to save your modifications".
code :
protected static Map< String ,CellStyle> makeCellStyles(XSSFWorkbook workbook) {
Map<String , CellStyle> styles = new HashMap<String , CellStyle>();
Font font = workbook.createFont();
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.LAVENDER.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
font.setBold(true);
style.setFont(font);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setBorderTop(CellStyle.BORDER_MEDIUM);
style.setBorderLeft(CellStyle.BORDER_MEDIUM);
style.setBorderRight(CellStyle.BORDER_MEDIUM);
style.setBorderBottom(CellStyle.BORDER_MEDIUM);
styles.put("groupHeader", style);
style = workbook.createCellStyle();
font = workbook.createFont();
font.setColor(HSSFColor.WHITE.index);
font.setBold(true);
style.setBorderTop(CellStyle.BORDER_MEDIUM);
style.setBorderLeft(CellStyle.BORDER_MEDIUM);
style.setBorderRight(CellStyle.BORDER_MEDIUM);
style.setBorderBottom(CellStyle.BORDER_MEDIUM);
style.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFont(font);
styles.put("rowHeader", style);
DataFormat format = workbook.createDataFormat();
style = workbook.createCellStyle();
style.setBorderRight(CellStyle.BORDER_MEDIUM);
style.setDataFormat(format.getFormat("# ##0"));
style.setAlignment(CellStyle.ALIGN_CENTER);
styles.put("borderData", style);
style = workbook.createCellStyle();
//style.setBorderBottom(CellStyle.BORDER_MEDIUM);
style.setBorderRight(CellStyle.BORDER_MEDIUM);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setDataFormat(format.getFormat("# ##0"));
styles.put("data", style);
return styles;
}
static private void writeXls() {
// Using XSSF for xlsx format, for xls use HSSF
//final String FILE_PATH = "F:/lesStats.xlsx";
try {
FileOutputStream fos = new FileOutputStream(statfile);
XSSFWorkbook workbook = new XSSFWorkbook();
DataFormat format = workbook.createDataFormat();
String si = "Fichier;total documents; documents corrects;"
+ "documents erronnees; erreurs formats ; "
+ "erreur dictionnaire ; erreurs index manquants ; erreurs chemin";
String[] entetes = si.split(";");
Sheet globalStat = workbook.createSheet("statistiques gobales");
setXlsProperties(workbook);
int cellIndex = 0;
int rowIndex = 0;
Row row = globalStat.createRow(rowIndex++);
row = globalStat.createRow(rowIndex++);
row = globalStat.createRow(rowIndex++);
Map<String ,CellStyle> styles = makeCellStyles(workbook);
for (int i = 0; i < 9; i++) {
if (i != 4)
row.createCell(i).setCellValue("");
else {
row.createCell(i).setCellValue("Type Erreurs");
}
}
for (int i = 4; i < 8; i++) {
row.getCell(i).setCellStyle(styles.get("groupHeader"));
// row.getCell(i).getCellStyle().setBorderTop(CellStyle.BORDER_MEDIUM);
}
row.getCell(7).getCellStyle().setBorderRight(CellStyle.BORDER_MEDIUM);
// (groupHeaderStyle);
globalStat.addMergedRegion(new CellRangeAddress(2, 2, 4, 7));
// row.getCell(4).setCellStyle(groupHeaderStyle);
row = globalStat.createRow(rowIndex++);
cellIndex = 0;
for (String val : entetes) {
row.createCell(cellIndex++).setCellValue(val);
row.getCell(cellIndex - 1).setCellStyle(styles.get("rowHeader"));
}
int fileIndex = 0;
for (Integer[] info : lesstats) {
row = globalStat.createRow(rowIndex++);
cellIndex = 0;
row.createCell(cellIndex++).setCellValue(filescecked.get(fileIndex++));
row.getCell(0).setCellStyle(styles.get("rowHeader"));
for (Integer i : info) {
row.createCell(cellIndex).setCellValue(i);
row.getCell(cellIndex).setCellStyle(styles.get("data"));
cellIndex++;
}
}
System.out.println(lesstats.size());
for (int i = 1; i <= lesstats.get(0).length; i++) {
row.getCell(i).setCellStyle(styles.get("borderData"));
}
row = globalStat.createRow(rowIndex);
row.createCell(0);
for (int i = 1; i < 8; i++) {
row.createCell(i);
Integer limit = 3 + lesstats.size();
String col = "";
col += (char) (65 + i);
col += "3";
col += ":";
col += (char) (65 + i);
col += limit.toString() + ")";
System.out.println("\tSUM(" + col);
row.getCell(i).setCellFormula("SUM(" + col);
row.getCell(i).setCellStyle(styles.get("rowHeader"));
row.getCell(i).getCellStyle().setAlignment(CellStyle.ALIGN_CENTER);
row.getCell(i).getCellStyle().setDataFormat(format.getFormat("# ##0"));
}
for (int i = 0; i < 9; i++)
globalStat.autoSizeColumn(i);
//workbook.close();
workbook.write(fos);
fos.close();
workbook.close();
System.out.println(statfile + " is successfully written");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I've just discovered that if i remove the call to setCellFormula the issue disappears which doesnt make any sense.

Related

how to read and validate blank lines from selenium excel

here in my code I am trying to read only the data from column "A" . Here in the screen shot I have attached how the sample data looks like. I am having an issue while reading the contents as its throwing null pointer exception because of the blank line. I need to verify the blank line as well . Please give me your thoughts
public void verifyAllSupportingLogs() throws Exception {
Sheet sheet = getFilenameSupportingLogs("c:\\DataFile");
int rowCount = sheet.getPhysicalNumberOfRows();
XSSFCell firstColumnCell = null;
int firstColumnRowCount = 0;
ArrayList<String> InnerArray = new ArrayList<>();
String cellValues = null;
String GetsupportingLogs1 = null;
for (int i = 0; i < rowCount; i++) {
try {
XSSFRow row = (XSSFRow) sheet.getRow(i);
firstColumnCell = row.getCell(0);
} catch (NullPointerException nullPointerException) {
System.out.println("Cell is null at index: " + i);
}
if (firstColumnCell != null) {
if (firstColumnCell.getStringCellValue().length() > 0) {
firstColumnRowCount = i;
}
}
}
for (int j = 0; j <= firstColumnRowCount; j++) {
XSSFRow row = (XSSFRow) sheet.getRow(j);
XSSFCell cell = row.getCell(0);
String valuesFromExcel = cell.getStringCellValue();
InnerArray.add(valuesFromExcel);
cellValues = InnerArray.toString();
}
String GetsupportingLogs = con.clickOnSupportingLogsTextbox(GetsupportingLogs1);
System.out.println("GetsupportingLogs" + GetsupportingLogs);
con.checkValueSupportingLogs(cellValues, GetsupportingLogs);
}
public void checkValueSupportingLogs(String GetsupportingLogs, String cellValue) throws Exception {
java.lang.String[] cellValue1 = cellValue.split("\n");
for (String cellValue2 : cellValue1) {
if (GetsupportingLogs.contains(cellValue2)) {
System.out.println("Success, this string is in the supporting logs.");
} else {
reportFailure("ERROR! This string is not in the supporting logs.");
}
}
}
Simply apply same check if cell is null.
Instead of:
for (int j = 0; j <= firstColumnRowCount; j++) {
XSSFRow row = (XSSFRow) sheet.getRow(j);
XSSFCell cell = row.getCell(0);
String valuesFromExcel = cell.getStringCellValue();
InnerArray.add(valuesFromExcel);
cellValues = InnerArray.toString();
}
use this:
XSSFCell cell = null;
for (int j = 0; j <= firstColumnRowCount; j++) {
XSSFRow row = (XSSFRow) sheet.getRow(j);
try {
cell = row.getCell(0);
}
catch (NullPointerException nullPointerException) {
System.out.println("Cell is null at index: " + j);
}
if (cell != null) {
String valuesFromExcel = cell.getStringCellValue();
InnerArray.add(valuesFromExcel);
cellValues = InnerArray.toString();
cell = null;
}
}
In case if different data types in the excel file, you can combine with this: Error : Cannot get a STRING value from a NUMERIC cell in Selenium

poi java code to merge cells based on common data

I have data in the above format in an excel file , I want to edit it as follows:
I have used the following code :
public void editExcelTemplate() throws FileNotFoundException, IOException
{
InputStream ExcelFileToRead = new FileInputStream("file.xls");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFSheet sheet = wb.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();
String cmp = "none";
for(int i=0;i<rows;i++)
{
Row row = sheet.getRow(i);
int col =row.getPhysicalNumberOfCells();
int colIndex = 1;
int v=0;
for(int j=0;j<col;j++)
{
String content = row.getCell(j).getStringCellValue();
if(!(content == cmp) && !(content.equals("none")))
{
if(!(cmp.equals("none")))
{
System.out.println("content: "+content);
System.out.println("cmp: "+cmp);
v= j;
System.out.println("row : "+i+"colst : "+(colIndex)+"colend : "+v);
if(!( v-colIndex == 0) && v>0)
{
System.out.println("row : "+i+"colst : "+(colIndex)+"colend : "+v);
sheet.addMergedRegion(new CellRangeAddress(i,i,colIndex-1,v-1));
System.out.println("merged");
}
}
}
if(!(content == cmp))
{
colIndex = v+1;
}
cmp = content;
}
}
FileOutputStream excelOutputStream = new FileOutputStream(
"file.xls");
wb.write(excelOutputStream);
excelOutputStream.close();
}
I endedup getting the following output :
Can anybody help me get an appropriate output ? The main purpose is to merge the cells with common data in the entire proces.

cannot get a numerical value from the excel cell

public Object[][] dataProviderMethod() throws IOException {
try {
file = new FileInputStream(new File("/Users/nanthakumar/Documents/workspace/Myna_Admin/src/com/myna/testdata/login.xls"));
workbook = new HSSFWorkbook(file);
sheet = workbook.getSheetAt(0);
row = sheet.getLastRowNum() + 1;
col = sheet.getRow(0).getLastCellNum();
data = new String[row][col];
for (i = 0; i < row; i++) {
rowvalue = sheet.getRow(i);
for (j = 0; j < col; j++) {
cellValue = rowvalue.getCell(j);
data[i][j] = cellValue.getStringCellValue();
System.out.println("The value is ----->" + data[i][j]);
}
workbook.close();
file.close();
}
} catch (FileNotFoundException nana) {
nana.printStackTrace();
}
return data;
}
This is my code and I tried to add the getnumericalCellvalue() instead of getStringCellValue() but that is not working for me.
first you have to check in the template excel whether the column is number or text.you can get the numerical value if and only if the column is of type number.so change the template excel and try

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;
}

How to add a new sheet into an existing xls file

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

Categories