I have been working on a highlighting cells in excel sheet after end of execution when i opened the processed file(.xlsx file) using Ms-excel-2007 i am facing two pop up's .here the specified code and images :
HSSFWorkbook xlsWB = new HSSFWorkbook(file1InputStream);
XSSFWorkbook xlsxWB = new XSSFWorkbook(file2InputStream);
CellStyle xlsxStyle = getCellStyle(xlsxWB);
int numbeoOfSheetsFile1 = xlsWB.getNumberOfSheets();
int numbeoOfSheetsFile2 = xlsxWB.getNumberOfSheets();
for (int sheetIndex = 0; sheetIndex < numbeoOfSheetsFile1 && sheetIndex < numbeoOfSheetsFile2; sheetIndex++) {
HSSFSheet sheetFile1 = xlsWB.getSheetAt(sheetIndex);
XSSFSheet sheetFile2 = xlsxWB.getSheetAt(sheetIndex);
int noOfRowsSheetFile1 = sheetFile1.getLastRowNum();
int noOfRowsSheetFile2 = sheetFile2.getLastRowNum();
if (noOfRowsSheetFile1 < noOfRowsSheetFile2) {
for (int vRow = noOfRowsSheetFile1; vRow <= noOfRowsSheetFile2 - 1; vRow++) {
sheetFile2.createRow(vRow).setRowStyle(xlsxStyle);
//sheetFile2.getRow(vRow).setRowStyle(xlsxStyle);
}
}
if (noOfRowsSheetFile1 > noOfRowsSheetFile2) {
for (int vRow = noOfRowsSheetFile2 + 1; vRow <= noOfRowsSheetFile1; vRow++) {
sheetFile2.createRow(vRow).setRowStyle(xlsxStyle);
//sheetFile2.getRow(vRow).setRowStyle(xlsxStyle);
}
}
for (int vRow = 0; vRow <= noOfRowsSheetFile1; vRow++) {
HSSFRow rwFile1 = sheetFile1.getRow(vRow);
XSSFRow rwFile2 = sheetFile2.getRow(vRow);
int noOfColSheetFile1 = sheetFile1.getRow(vRow).getLastCellNum();
int noOfColSheetFile2 = 0;
try {
noOfColSheetFile2 = sheetFile2.getRow(vRow).getLastCellNum();
} catch (NullPointerException e) {
rwFile2 = sheetFile2.createRow(vRow);
noOfColSheetFile2 = 0;
}
// Coloring of mismatch columns
if (noOfColSheetFile1 < noOfColSheetFile2) {
for (int vCol = noOfColSheetFile1 + 1; vCol <= noOfColSheetFile2; vCol++) {
rwFile2.createCell(vCol);
//rwFile2.getCell(vCol).setCellStyle(xlsxStyle);
}
}
if (noOfColSheetFile1 > noOfColSheetFile2) {
for (int vCo2 = noOfColSheetFile2 + 1; vCo2 <= noOfColSheetFile1; vCo2++) {
rwFile2.createCell(vCo2);
//rwFile2.getCell(vCo2).setCellStyle(xlsxStyle);
}
}
for (int vCol = 0; vCol < noOfColSheetFile1; vCol++) {
//System.out.println("vCol>>" + vCol + "--vRow>>" + vRow);
HSSFCell cellFile1 = rwFile1.getCell(vCol);
XSSFCell cellFile2 = rwFile2.getCell(vCol);
String cellFile1Value = null;
if (null != cellFile1) {
cellFile1Value = cellFile1.toString();
}
String cellFile2Value = null;
if (null != cellFile2) {
cellFile2Value = cellFile2.toString();
}
if ((null == cellFile1Value && null != cellFile2Value) || (null != cellFile1Value && null == cellFile2Value) || (null != cellFile1Value && cellFile1Value.compareTo(cellFile2Value) != 0)) {
if ((null != cellFile1Value && !cellFile1Value.isEmpty()) || (null != cellFile2Value && ! cellFile2Value.isEmpty())) {
CellValues cellValues = new CellValues();
cellValues.setValue1(cellFile1Value);
cellValues.setValue2(cellFile2Value);
cellValues.setCellRow(vRow);
cellValues.setCellColumn(vCol);
scenarioResultDetails.addDifference(cellValues);
XSSFCell cellDiff = rwFile2.getCell(vCol);
if (null == cellDiff) {
cellDiff = rwFile2.createCell(vCol);
}
cellDiff.setCellStyle(xlsxStyle);
}
}
}
}
}
String fileDiff = file2.replace(".xls", "_diff.xls");
FileOutputStream fileOut = new FileOutputStream(fileDiff);
xlsxWB.write(fileOut);
if (null != fileOut) {
try {
fileOut.close();
} catch (Exception e) {
}
}
if (scenarioResultDetails.getDifferencesList().size() > 0) {
scenarioResultDetails.setResult(false);
scenarioResultDetails.setResultText("Not Matched");
scenarioResultDetails.setDiffExcel(fileDiff);
} else {
scenarioResultDetails.setResult(true);
scenarioResultDetails.setResultText("Matched");
}
return scenarioResultDetails;
}
public static void openFile(String fileName){
ReportGenerator.getDriver().get("file://"+fileName);
}
private static CellStyle getCellStyle(XSSFWorkbook xssfWorkbook){
CellStyle style = xssfWorkbook.createCellStyle();
Font font = xssfWorkbook.createFont();
font.setColor(IndexedColors.BLACK.getIndex());
style.setFont(font);
style.setFillForegroundColor(HSSFColor.YELLOW.index);
style.setFillBackgroundColor(HSSFColor.YELLOW.index);
style.setFillPattern(CellStyle.ALIGN_RIGHT);
return style;
}
}
This behavior is still (or again) present. I'm using version 2.4.1 of the NuGet NPOI package which apparently has a FontHeight property bugfix, but it also introduced this.
The problem is that the font size the font returned by xssfWorkbook.createFont(); is way small. You have to set it explicitly like so:
IFont font = excel.CreateFont();
font.FontHeightInPoints = 11;
Also I got similar errors when overwriting a file that was previously repaired. Make sure you write to a clean/new file every time you change your code so no previous corruptions get in the way.
Full example:
/// <summary>
/// Return style for header cells.
/// </summary>
/// <returns></returns>
private static ICellStyle GetHeaderStyle(this XSSFWorkbook excel)
{
IFont font = excel.CreateFont();
font.IsBold = true;
//Added this explicitly, initial font size is tiny
font.FontHeightInPoints = 11;
ICellStyle style = excel.CreateCellStyle();
style.FillForegroundColor = IndexedColors.Grey25Percent.Index;
style.FillPattern = FillPattern.SolidForeground;
style.FillBackgroundColor = IndexedColors.Grey25Percent.Index;
style.BorderBottom = style.BorderLeft = style.BorderRight = style.BorderTop = BorderStyle.Thin;
style.BottomBorderColor = style.LeftBorderColor = style.RightBorderColor = style.TopBorderColor = IndexedColors.Black.Index;
style.SetFont(font);
return style;
}
I have been thinking of days for the solution. Anyway, I am doing a program where the apache will copy the whole sheet to another sheet in a workbook. Currently, my code can copy the contents but not the colour and format of the sheet. Please assist as I really unsure on how to proceed. Thanks.
int rowReadIndent = 0;
int columnReadIndent = 0;
int rowWriteIndent = 0;
int columnWriteIndent = 0;
ArrayList<ArrayList<ArrayList<Object>>> lists = new ArrayList<ArrayList<ArrayList<Object>>>();
ArrayList<ArrayList<ArrayList<Short>>> cellColorLists = new ArrayList<ArrayList<ArrayList<Short>>>();
//ArrayList<ArrayList<ArrayList<XSSFCellStyle>>> cellStyleLists = new ArrayList<ArrayList<ArrayList<XSSFCellStyle>>>();
ArrayList<String> sheetNameList = new ArrayList<String>();
for(int i = 0; i < fileArrayList.size(); i++) {
OPCPackage pkg = OPCPackage.open(new FileInputStream(desktop + "/test/" + fileArrayList.get(i)));
XSSFWorkbook wb = new XSSFWorkbook(pkg);
Sheet sheet1 = wb.getSheetAt(0);
lists.add(new ArrayList<>());
//cellStyleLists.add(new ArrayList<ArrayList<XSSFCellStyle>>());
cellColorLists.add(new ArrayList<>());
sheetNameList.add(sheet1.getSheetName());
for(int j = 0; j < 50; j++) {
Row row1 = sheet1.getRow(j + rowReadIndent);
lists.get(i).add(new ArrayList<>());
//cellStyleLists.get(i).add(new ArrayList<XSSFCellStyle>());
cellColorLists.get(i).add(new ArrayList<>());
if(row1 != null) {
for(int k = 0; k < 50; k++) {
Cell cell1 = row1.getCell(k + columnReadIndent, Row.RETURN_BLANK_AS_NULL);
if(cell1 != null){
Object o = null;
int type = cell1.getCellType();
if(type == Cell.CELL_TYPE_FORMULA) {
type = cell1.getCachedFormulaResultType();
}
switch (type) {
case Cell.CELL_TYPE_STRING:
o = cell1.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell1)) {
o = cell1.getDateCellValue();
} else {
o = cell1.getNumericCellValue();
}
break;
case Cell.CELL_TYPE_BOOLEAN:
o = cell1.getBooleanCellValue();
break;
}
//XSSFCellStyle cellStyle = new XSSFCellStyle(new StylesTable());
//cellStyle.cloneStyleFrom(cell1.getCellStyle());
//cellStyleLists.get(i).get(j).add(cellStyle);
XSSFCellStyle cellStyle = new XSSFCellStyle(new StylesTable());
cellStyle = (XSSFCellStyle) cell1.getCellStyle();
cellColorLists.get(i).get(j).add(cellStyle.getFillBackgroundColor());
lists.get(i).get(j).add(o);
}
else {
lists.get(i).get(j).add(null);
}
}
}
}
pkg.close();
}
OPCPackage pkg1 = OPCPackage.open(new FileInputStream(desktop + "/test/Output Graph.xlsx"));
XSSFWorkbook wb1 = new XSSFWorkbook(pkg1);
FileOutputStream stream = new FileOutputStream(desktop + "/Output Graph4.xlsx" /*+ name + ".xlsx"*/);
for(int i = 0; i < lists.size(); i++) {
Sheet sheet1 = wb1.createSheet();
wb1.setSheetName(wb1.getSheetIndex(sheet1), sheetNameList.get(i));
for(int j = 0; j < lists.get(i).size(); j++) {
Row row1 = sheet1.createRow(j + rowWriteIndent);
for(int k = 0; k < lists.get(i).get(j).size(); k++) {
Cell cell1 = row1.createCell(k + columnWriteIndent);
//cell1.setCellStyle(cellStyleLists.get(i).get(j).get(k));
//XSSFCellStyle cellStyle = new XSSFCellStyle(new StylesTable());
//cellStyle = (XSSFCellStyle) cell1.getCellStyle();
//cellStyle.setFillBackgroundColor(cellColorLists.get(i).get(j).get(k));
if(lists.get(i).get(j).get(k) != null) {
switch (lists.get(i).get(j).get(k).getClass().getSimpleName()) {
case "String":
cell1.setCellValue((String)lists.get(i).get(j).get(k));
break;
case "Date":
cell1.setCellValue((Date)lists.get(i).get(j).get(k));
break;
case "Double":
cell1.setCellValue((Double)lists.get(i).get(j).get(k));
break;
case "Boolean":
cell1.setCellValue((Boolean)lists.get(i).get(j).get(k));
break;
}
}
}
}
}
/* Sheet sheet1;
Row row1;
Row row2;
Cell cell1;
for(int j = 0; j < lists.size(); j++) {
wb1.cloneSheet(0);
sheet1 = wb1.getSheetAt(j+1);
row1 = sheet1.createRow(1);
row2 = sheet1.createRow(0);
for(int i = 0; i < lists.get(j).size(); i++) {
cell1 = row1.createCell(i);
cell1.setCellType(Cell.CELL_TYPE_NUMERIC);
//cell1.setCellValue(lists.get(j).get(i));
System.out.println("Stored: "+lists.get(j).get(i));
}
for(int i = 0; i < lists1.get(j).size(); i++) {
cell1 = row2.createCell(i);
cell1.setCellType(Cell.CELL_TYPE_NUMERIC);
cell1.setCellValue(lists1.get(j).get(i));
System.out.println("Stored: "+lists1.get(j).get(i));
}
}*/
wb1.write(stream);
stream.close();
pkg1.close();
Desktop.getDesktop().open(new File(desktop + "/Output Graph4.xlsx"));
} catch (FileNotFoundException ex) {
Logger.getLogger(status.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(status.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidFormatException ex) {
Logger.getLogger(status.class.getName()).log(Level.SEVERE, null, ex);
}
}
I really have some problems with my code. Really appreciate it if any of you would help me. Below is my code and 2 screenshots of what it looks like and how it should looks like when the code is being executed.
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename="+ ReportID + ".xlsx");
String excelFileName = "C:\\Test.xlsx";
XSSFWorkbook w = new XSSFWorkbook();
System.out.println("w: " + w);
XSSFSheet s = w.createSheet(ReportID);
System.out.println("s: " + s);
// Report Title
s.createRow(0).createCell(0).setCellValue(Title);
System.out.println("Title: " + Title);
// Populate the worksheet
int _col_cnt = HeadersLabel.length;
XSSFRow row = s.createRow(_col_cnt);
System.out.println("HeadersLabel: " + _col_cnt);
for (int c = 0; c < _col_cnt; c++) {
// Construct the header row
String _h = HeadersLabel[c];
System.out.println("_h: " + _h);
if (_h != null) {
XSSFCell hd = row.createCell(c);
hd.setCellValue(_h);
}
int r = 3;
for (Iterator iter = Cells.iterator();iter.hasNext();) {
Object[] _o = (Object[]) iter.next();
currentRow = s.createRow(r);
for(int colNum = 0; colNum < _col_cnt; colNum++){
XSSFCell currentCell =currentRow.createCell(colNum);
if (CellDataType[c].equals("STRING")
|| CellDataType[c].equals("VARCHAR")) {
String _l = (String) _o[colNum];
if (_l != null) {
currentCell.setCellValue(_l);
System.out.println("Data: " + _l);
}
}
else if (CellDataType[c].equals("DOUBLE")) {
Double _D = (Double) _o[c];
if (_D != null) {
//XSSFCell cell = rowData.createCell(c);
cell.setCellValue(_D);
}
} else if (CellDataType[c].equals("INTEGER")) {
Integer _I = (Integer) _o[c];
if (_I != null) {
//XSSFCell cell = rowData.createCell(c);
cell.setCellValue(_I);
}
} else if (CellDataType[c].equals("DATE")) {
Date _aDate = (Date) _o[c];
if (_aDate != null) {
//XSSFCell cell = rowData.createCell(c);
cell.setCellValue(_aDate);
}
} else if (CellDataType[c].equals("TIMESTAMP")) {
Timestamp _aTimestamp = (Timestamp) _o[c];
Date _aDate = Timestamp2Date(_aTimestamp);
if (_aDate != null) {
//XSSFCell cell = rowData.createCell(c);
cell.setCellValue(_aDate);
}
}
r++;
}
}
FileOutputStream fos = new FileOutputStream(excelFileName);
//w.write(response.getOutputStream());
w.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
context.responseComplete();
}
The XLSX excel did not manage to capture some data. The first two column is empty when there is suppose to be data appearing. Only the third column has the data.
What it looks like now: https://www.dropbox.com/s/2vfxsootyln6qq5/Capture3.JPG What it suppose to be like: https://www.dropbox.com/s/d0yctgk4pywh140/Capture2.JPG
I am not sure about the data source... However I have tried to solve your problem As far as possible. Please change it wherever you need.
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename="+ ReportID + ".xlsx");
String excelFileName = "C:\\Test.xlsx";
XSSFWorkbook w = new XSSFWorkbook();
System.out.println("w: " + w);
XSSFSheet s = w.createSheet(ReportID);
System.out.println("s: " + s);
// Report Title
s.createRow(0).createCell(0).setCellValue(Title);
System.out.println("Title: " + Title);
// Populate the worksheet
int _col_cnt = HeadersLabel.length;
XSSFRow row = s.createRow(_col_cnt);
System.out.println("HeadersLabel: " + _col_cnt);
//For Headers
int headerRowNum = 2; //for App, ShortName, LongName
XSSFRow currentRow = s.createRow(headerRowNum);
for(int headerCol =0; headerCol <_col_cnt; headerCol++){
currentRow.createCell(headerCol).setCellValue(HeadersLabel[headerCol]);
}
// for Date entry
for(int dataRow=3;dataRow < 20;dataRow++){
currentRow = s.createRow(dataRow);
for(int colNum=0;colNum<_col_cnt;colNum++){
XSSFCell currentCell =currentRow.createCell(colNum);
if (CellDataType[c].equals("STRING") || CellDataType[c].equals("VARCHAR")) {
String _l = (String) _o[c];
if (_l != null) {
currentCell.setCellValue(_l);
}
} else if (CellDataType[c].equals("DOUBLE")) {
Double _D = (Double) _o[c];
if (_D != null) {
currentCell.setCellValue(_D);
}
} else if (CellDataType[c].equals("INTEGER")) {
Integer _I = (Integer) _o[c];
if (_I != null) {
currentCell.setCellValue(_I);
}
} else if (CellDataType[c].equals("DATE")) {
Date _aDate = (Date) _o[c];
if (_aDate != null) {
currentCell.setCellValue(_aDate);
}
} else if (CellDataType[c].equals("TIMESTAMP")) {
Timestamp _aTimestamp = (Timestamp) _o[c];
Date _aDate = Timestamp2Date(_aTimestamp);
if (_aDate != null) {
currentCell.setCellValue(_aDate);
}
}
}
}
}
}
I need to fetch data from multiple tables and export into excel sheet for each table. I don't want to use the getXXX() method as there are large number of columns and I don’t know the data type of each column. I need to fetch an entire row and store in the result in List.
I fetched each column using getObject() and also the class type using MetaData.getColumnClassName().
For example
Object val = resultSet.getObject(i);
I try to cast this val to its actual type using getColumnClassName() but it gives me an error while casting.
Can anyone please help me.
public class Row {
public Map<Object, Class> row;
public static Map<String, Class> TYPE;
static {
TYPE = new HashMap<String, Class>();
TYPE.put("INTEGER", Integer.class);
TYPE.put("NUMERIC", BigDecimal.class);
TYPE.put("DOUBLE", Double.class);
TYPE.put("VARCHAR2", String.class);
}
public Row() {
row = new HashMap<Object, Class>();
}
public <t> void add(t data) {
row.put(data, data.getClass());
}
public void add(Object data, String sqlType) {
add((Row.TYPE.get(sqlType)) data);
}
public static void formTable(ResultSet rs, List<Row> table) throws SQLException {
if(rs == null)
return;
ResultSetMetaData rsmd = rs.getMetaData();
int colCt = rsmd.getColumnCount();
while(rs.next()) {
Row row = new Row();
for(int i = 0; i < colCt; i++) {
row.add(rs.getObject(i), rsmd.getColumnTypeName(i));
}
table.add(row);
}
}
public static void main(String[] args) {
}
}
Try this code:
Connection connection = DriverManager.getConnection("URL", "USERNAME", "PASSWORD");
PreparedStatement statement = connection.prepareStatement("select * from table");
ResultSet resultSet = statement.executeQuery();
if (resultSet != null) {
while (resultSet.next()) {
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
int type = resultSetMetaData.getColumnType(i);
if (type == Types.VARCHAR || type == Types.CHAR) {
System.out.println(resultSet.getString(i));
} else {
System.out.println(resultSet.getLong(i));
}
}
System.out.println("-----------");
}
}
You should extend it with other datatypes.
Step 1: get the metadata
ResultSetMetaData rsmd;
rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
int[] columnsType = new int[numColumns + 1];
columnsType[0] = 0;
for (int i = 1; i <= numColumns; i++)
columnsType[i] = rsmd.getColumnType(i);
Step 2: fetch a row at a time from the result set and check the data type
String s;
Object o;
while (rs.next()) {
for (int i = 1; i <= numColumns; i++) {
if (columnsType[i] == java.sql.Types.NUMERIC || columnsType[i] == java.sql.Types.CHAR || columnsType[i] == java.sql.Types.VARCHAR) {
s = rs.getString(i);
} else if (columnsType[i] == java.sql.Types.NVARCHAR) {
s = rs.getNString(i);
} else if (columnsType[i] == java.sql.Types.BOOLEAN) {
// TODO
} else if (columnsType[i] == java.sql.Types.FLOAT || columnsType[i] == java.sql.Types.DOUBLE) {
// TODO
} else if (columnsType[i] == java.sql.Types.TINYINT || columnsType[i] == java.sql.Types.SMALLINT || columnsType[i] == java.sql.Types.INTEGER || columnsType[i] == java.sql.Types.BIGINT) {
// TODO
} else if (columnsType[i] == java.sql.Types.DATE || columnsType[i] == java.sql.Types.TIMESTAMP) {
// TODO
} else {
o = rs.getObject(i);
}
}
}
Step 3: fill the blanks and add the exception handling
Step 4: write to Excel (inside the loop)
public class EXECUTEQUERY implements Module {
private static final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private String userId;
String result = "";
String resp = "";
static int count = 1;
private final Logger log = Logger.getLogger("EXECUTEQUERY");
private void dbg(String msg) {
log.info(userId + ":" + msg);
}
private void dbg(Exception ex) {
log.info(ex.getMessage());
ex.printStackTrace();
}
private void uDbg(String msg) {
log.info(userId + " :" + msg);
}
private void uDbg(Exception ex) {
uDbg(ex.getMessage());
ex.printStackTrace();
}
public String main(UserContext userContext, String reqXml) {
dbg("Query recieved is " + reqXml);
String resp;
userId = userContext.getUserId();
if (userContext.getAction().equals("EXECUTEQUERY")) {
if (reqXml == null || reqXml.equals("")) {
result = "!Please Enter the query";
} else {
result = getQueryResult(userContext, reqXml);
}
}
return result;
}
/***
*
* for adding search record in backend created by #shyamlal yadav
* #param userContext
* #param reqXml
*/
public void addQueryLog(UserContext userContext, String reqXml) {
dbg("inside addQueryLog methos request is " + reqXml);
userId = userContext.getUserId();
dbg( userId +"this user is selecting value from screen");
System.out.println("recieve request is " + reqXml);
PreparedStatement pStmt = null;
Connection eodConn = null;
dbg("addQueryLog recieved for log " + reqXml);
Date date = new Date();
java.sql.Date sqlDate = new java.sql.Date( date.getTime());
eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();
try {
pStmt = eodConn.prepareStatement("insert into EOD_QRY_EXEC_LOG (QRY_EXEC_TIMESTAMP, QRY_TEXT,OPERATOR_ID)\n"
+ " values (?,?,?)");
pStmt.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
pStmt.setString(2, reqXml);
pStmt.setString(3, userId);
pStmt.executeQuery();
} catch (SQLException ex) {
dbg("Exception is " + ex);
return;
}
EODConnectionFactory.returnFCConnectionToPool(eodConn);
return;
}
/*
This method returns query excecuted table data with separators.
#Shaymlal,
*/
public String getQueryResult(UserContext userContext, String reqXml) {
String field_value = "";
String lsitofquery = "";
String resultlist = "";
dbg("Inside getQueryResult method");
Connection eodConn = null;
Statement stmt = null;
eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();
try {
stmt = eodConn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(reqXml);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
dbg("Total no of column is:" + columnCount);
int rsCount = 1;
while (rs.next()) {
if (rsCount == 1) {
for (int i = 1; i <= columnCount; i++) {
resultlist += "~" + rsmd.getColumnName(i);
}
}
for (int i = 1; i <= columnCount; i++) {
field_value += "~" + rs.getString(i);
}
field_value = field_value + "~<>";
lsitofquery = resultlist + "~>" + field_value;
rsCount = rsCount + 1;
}
} catch (Exception ex) {
dbg("Exception is " + ex);
return "!Exception invalid query: " + ex;
}
EODConnectionFactory.returnFCConnectionToPool(eodConn);
// return rowCount > 0 ? lsitofquery+">" : "!Table is Empty" ;
addQueryLog(userContext,reqXml);
return lsitofquery + ">";
}
}
I have created a Batch Reporting using Apache POI. I need to know how to add Headers to both sheets. I used getHeader() but that adds same Headers for both sheets and I need to add different headers to both sheets. My code is following.
Excel Writer:
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);
createColumnHeaderRow(sheet,columns,numHeaderRows,columnsStyle);
int rowCtr1 = numHeaderRows;
for( int i = 0; i < data.length; i++) {
if (i > data.length -2)
++rowCtr1;
else
rowCtr1 = rowCtr1 + 2;
createRow(sheet, 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");
arialBoldFont.setFontHeightInPoints((short) 12);
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 which includes Headers, footer, and columns:
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("Arial");
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("Arial");
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;
}
}
Report Generator Abstract class
public void generateExcelReport(Map map, String startDate, String endDate) throws IOException {
ExcelWriter writer = new ExcelWriter();
writer.writeExcelFile( getXlsFilename(), getColumnNames(), getData(map),
getStyles(writer.getWorkbook()), getColumnsStyle(writer.getWorkbook()),
getHeader(startDate, endDate), getFooter());
Report Driver:
public class ReportDriver {
static Logger log = Logger.getLogger(ReportDriver.class.getName());
public static void main (String args[]){
if (args.length == 0) {
log.error("Usage - ReportDriver [Day|Week|Month|Year]");
System.exit(1);
}
String reportPeriod = args[0];
log.info("Begin Prior " + reportPeriod + " Report");
String dir = "c:\\excsbatch\\report\\";
Dates dates = new Dates();
dates.setDates(reportPeriod);
String startDate = dates.getStartDate();
String endDate = dates.getEndDate();
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
Calendar cal = Calendar.getInstance();
String timeStamp = dateFormat.format(cal.getTime());
String fileName = "prior" + reportPeriod + "Report" + timeStamp;
SummaryDAO dao = new SummaryDAO();
Map map = dao.extractData(startDate, endDate);
SummaryReportGenerator report = new SummaryReportGenerator(dir, fileName);
try {
report.generateExcelReport(map, startDate, endDate);
}
catch(Exception e) {
log.error(e.getMessage());
System.exit(2);
}
log.info("End Prior " + reportPeriod + " Report");
}
}