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 + ">";
}
}
Related
How to not duplicate when adding data in JTable because when I am adding in JTable it always duplicate the same data.
public void buyproduct() {
String name = code_cart1.getText();
try {
con = Connector.getConnection();
PreparedStatement pst = con.prepareStatement("SELECT `Code`, `Category`, `ProductName`, `Size`, `Quantity`, `Price`, `Sub-Total` FROM `product_table` WHERE Code = ?");
pst.setString(1, name);
rs = pst.executeQuery();
while (rs.next()) {
int currentqty = rs.getInt("Quantity");
int pricenew = Integer.parseInt(price_cart1.getText());
int qtynew = Integer.parseInt(quantity_cart1.getText());
int tot = pricenew * qtynew;
if (qtynew > currentqty || qtynew == 0) {
JOptionPane.showMessageDialog(this, "Out of Stock!");
} else {
DefaultTableModel model = (DefaultTableModel) cart_Display.getModel();
model.addRow(new Object[]{code_cart1.getText(),
category_cart1.getText(),
productname_cart1.getText(),
size_cart1.getText(),
quantity_cart1.getText(),
price_cart1.getText(),
tot});
int sum = 0;
for (int i = 0; i < cart_Display.getRowCount(); i++) {
sum = sum + Integer.parseInt(cart_Display.getValueAt(i, 6).toString());
}
SubTotal_Cart_text.setText(Integer.toString(sum));
SubTotal_Cart_text1.setText(Integer.toString(sum));
code_cart1.setText("");
category_cart1.setText("");
productname_cart1.setText("");
size_cart1.setText("");
quantity_cart1.setText("");
price_cart1.setText("");
}
}
} catch(Exception ex) {
}
}
My table looks like this, everything works and everything is OK) I need that if the condition ARRIVAL = 0 or DEPART = 0 is met, then the text color in the whole row was of a different color, for example, red or black, it does not matter, I can not figure out how to change it, maybe it's easy, I'm new) I haven't found an answer to this question in other questions
private void setTableSettingsReport() {
jTblReport.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jTblReport.setRowSelectionAllowed(true);
jTblReport.setAutoCreateRowSorter(true);
jTblReport.getTableHeader().setReorderingAllowed(false);
String[] dbColNames = new String[13];
dbColNames[0] = "ID";
dbColNames[1] = "Имя";
dbColNames[2] = "Фамилия";
dbColNames[3] = "Отчество";
dbColNames[4] = "Дата прихода с ";
dbColNames[5] = "Дата прихода до";
dbColNames[6] = "Прибытие";
dbColNames[7] = "Дата ухода с ";
dbColNames[8] = "Дата ухода до";
dbColNames[9] = "Убытие";
dbColNames[10] = "Причина опоздания";
dbColNames[11] = "Причина раннего ухода";
dbColNames[12] = "ID лица";
// dbColNames[8] = "Дата начала";
// dbColNames[9] = "Дата окончания";
tm.setColumnIdentifiers(dbColNames);
jTblReport.setModel(tm);
jTblReport.setSelectionForeground(Color.white);
jTblReport.setSelectionBackground(Color.red);
jTblReport.getColumnModel().getColumn(0).setPreferredWidth(10);
jTblReport.getColumnModel().getColumn(1).setPreferredWidth(60);
jTblReport.getColumnModel().getColumn(2).setPreferredWidth(60);
jTblReport.getColumnModel().getColumn(3).setPreferredWidth(60);
jTblReport.getColumnModel().getColumn(4).setPreferredWidth(60);
jTblReport.getColumnModel().getColumn(5).setPreferredWidth(60);
jTblReport.getColumnModel().getColumn(6).setPreferredWidth(60);
jTblReport.getColumnModel().getColumn(7).setPreferredWidth(60);
jTblReport.getColumnModel().getColumn(8).setPreferredWidth(60);
jTblReport.getColumnModel().getColumn(9).setPreferredWidth(60);
jTblReport.getColumnModel().getColumn(10).setPreferredWidth(60);
jTblReport.getColumnModel().getColumn(10).setPreferredWidth(60);
jTblReport.getColumnModel().getColumn(10).setPreferredWidth(60);
}
public void searchIdentificationsReport(boolean all) {
int z = 0;
while (z < tm.getRowCount()) {
tm.removeRow(z);
}
Statement statement = null;
try {
statement = getDbConnection().createStatement();
String sql = "select a.id, pr.p_name,pr.p_surname,pr.p_patronic, a.date_arrival_from,a.date_arrival_to, a.arrival,a.date_departure_from,a.date_departure_to, a.depart, a.arrival_comment, a.depart_comment,a.prsn_id "
+ " FROM bio.persons pr, attendance a where pr.p_id=a.prsn_id and a.date<=CURDATE() ";
if (cbPersons.getSelectedItem() != null && model.getSelectedItem() != null) {
CodeValueDTO dto = (CodeValueDTO) model.getSelectedItem();
sql += " and pr.p_id='" + dto.getId() + "'";
}
if (!all) {
sql += " and (ARRIVAL =0 or DEPART=0)";
}
statement.execute(sql);
ResultSet rs = statement.getResultSet();
while (rs.next()) {
Object[] objects = new Object[13];
for (int i = 0; i < 13; i++) {
objects[i] = rs.getObject(i + 1);
}
if (rs.getInt(7) == 0) {
objects[6] = "Нет";
} else {
objects[6] = "Да";
}
if (rs.getInt(10) == 0) {
objects[9] = "Нет";
} else {
objects[9] = "Да";
}
tm.addRow(objects);
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
statement.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
dbColNames[6] = "Прибытие"; dbColNames[9] = "Убытие";
these are the same fields depending on which you need to change the color of the entire line
You need to set a own cell-renderer for this JTable (I assume you are using a JTable).
public class MyCellRenderer extends DefaultTableCellRenderer{
private int columNum = 0;
public MyCellRenderer(int columNum) {
// TODO Auto-generated constructor stub
this.columNum = columNum;
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
// TODO Auto-generated method stub
Object object = table.getValueAt(row, this.columNum);
if(object.equals("yourValue")) {
setBackground(Color.RED);
}
return this;
}
}
And you need to set this renderer to your jtable right after creating it.
jTabReport.setDefaultRenderer(Object.class, new MyCellRenderer(3));
For that you create a class like this and extend from DefaultTableCellRenderer and overwrite the getTableCellRendererComponent.
The constructor gets passed the columnumber where youre "arival" information is stored. For each cell in the row you check if the specified colum contains arival = 0 or not (This must be always the same colum). If so set the background. "yourValue" is just an example.
I tried to make an exporting data to PDF but when I try to export it, the pdf can't show up like "no data found"
this code on bean
public JasperPrint exportTo() {
if(this.listReportMaster == null || this.listReportMaster.isEmpty()){
FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found");
RequestContext.getCurrentInstance().showMessageInDialog(messageFailed);
return null;
}
String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/report/PRPKReportPDF.jasper");
JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(this.listReportMaster);
try {
JasperPrint jasperPrint = JasperFillManager.fillReport(path, null, beanCollectionDataSource);
return jasperPrint;
} catch (JRException e) {
e.printStackTrace();
return null;
}
}
public void exportToPdf(ActionEvent actionEvent){
if(this.lazyMasterReportDataModel != null){
System.out.println("masuk exporttopdf");
String sql = ((LazyMasterReportDataModel) this.lazyMasterReportDataModel).getSqlReportPrint();
List<Object> listObject = ((LazyMasterReportDataModel) this.lazyMasterReportDataModel).getObjectSqlListReportPrint();
this.listReportMaster = reportMasterPRPKController.getPRPKForReport(sql, listObject);
JasperPrint jasperPrint = exportTo();
String fileName = "PRPKNew_Report".concat("_").concat(".pdf");
if(jasperPrint != null) reportMasterPRPKController.exportToPDF(fileName, jasperPrint);
else System.out.println("jasperprint null");
}else{
System.out.println("keluar exporttopdf");
FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found");
RequestContext.getCurrentInstance().showMessageInDialog(messageFailed);
}
}
every I try to export it, always show "no data found" which is the program run this code FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found"); and which meam the "this.lazyMasterReportDataModel" is null but when I check it again, there's nothing wrong on code, I don't know if it have a wrong code or deficiency code
this the lazy code
List<ReportMasterPRPK> listMasterPRPK = new ArrayList<>();
ReportMasterPRPKQuery reportMasterPRPKQuery = new ReportMasterPRPKQuery();
Page page = new Page();
String order = "GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY a.created_date ";
String columname = "";
String sql = "";
List<Object> objectSqlList = new ArrayList<>();
String sqlReport = "";
String sqlReportPrint = "";
List<Object> objectSqlListReport = new ArrayList<>();
List<Object> objectSqlListReportPrint = new ArrayList<>();
String flag;
public LazyMasterReportDataModel() {
}
public LazyMasterReportDataModel(String flag) { //ini
this.flag = flag;
}
public LazyMasterReportDataModel(String sqlReport, List<Object> objectSqlListReport) {
this.sqlReport = sqlReport;
this.objectSqlListReport = objectSqlListReport;
}
#Override
public List<ReportMasterPRPK> load(int first, int pageSize, String sortField, SortOrder sortOrder,
Map<String, Object> filters) {
page.setLimit(pageSize);
page.setOffset(first);
if(this.sqlReport != null){
this.sql = this.sqlReport;
this.objectSqlList = this.objectSqlListReport;
}else{
sql = "";
objectSqlList = new ArrayList<>();
//objectSqlList.clear();
}
if(flag != null){ //ini
if(flag.equals("no selected")){
sql = sql+" AND c.is_selected = 'n' ";
}
}
if (filters != null){
for(String key: filters.keySet()){
String filterColumnName = "";
for(Field field : ReportMasterPRPK.class.getDeclaredFields()){
if(field.getName().equals(key)) filterColumnName = field.getAnnotation(Column.class).value();
}
if(filters.get(key) instanceof String){
if("receivedDate".equals(key)){
if(((String)filters.get(key)).trim().length() > 20){
String startDate = "'" + filters.get(key).toString().substring(0, 10) + "'";
String endDate = "'" + filters.get(key).toString().substring(11, 21) + "'";
sql = sql + " AND " + filterColumnName + " BETWEEN " + startDate + " AND " + endDate+ " ";
}
}else{
if(((String) filters.get(key)).trim().length() > 0){
sql = sql+"AND "+filterColumnName+" ILIKE ? ";
String value = "%"+filters.get(key)+"%";
objectSqlList.add(value);
}
}
}else{
if(((String[]) filters.get(key)).length > 0){
sql = sql+" AND "+filterColumnName+" in ";
String value = "(";
for(String string : (String[]) filters.get(key)){
value = value+"'"+string+"',";
}
value = value.substring(0, value.length()-1)+") ";
sql = sql + value;
}
}
}
}
if(sortField != null){
for(Field field : ReportMasterPRPK.class.getDeclaredFields()){
if(field.getName().equals(sortField)) columname = field.getAnnotation(Column.class).value();
}
if(sortOrder.toString().equals("ASCENDING")) order = " ASC";
else order = " DESC";
sql = sql+" GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY "+columname+" "+order;
System.out.println("sql sort: "+sql+" : "+objectSqlList.size());
}else{
sql = sql + order;
}
sqlReportPrint = sql;
objectSqlListReportPrint = objectSqlList;
this.listMasterPRPK = reportMasterPRPKQuery.retrivePage(page, sql, objectSqlList.toArray());
int dataSize = reportMasterPRPKQuery.retrieveMaxRow(sql, objectSqlList.toArray());
this.setRowCount(dataSize);
//objectSqlList.clear();
if(this.sqlReport != null){
this.sql = this.sqlReport;
this.objectSqlList = this.objectSqlListReport;
}else{
sql = "";
objectSqlList.clear();
}
order = "GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY a.created_date ";
return listMasterPRPK;
}
public List<ReportMasterPRPK> calculateRownum(List<ReportMasterPRPK> listMasterPRPK, int first){
int i = 1;
for (ReportMasterPRPK masterPRPK : listMasterPRPK) {
masterPRPK.setRownum(first + i);
i++;
}
return listMasterPRPK;
}
public String getSqlReportPrint() {
return sqlReportPrint;
}
public void setSqlReportPrint(String sqlReportPrint) {
this.sqlReportPrint = sqlReportPrint;
}
public List<Object> getObjectSqlListReportPrint() {
return objectSqlListReportPrint;
}
public void setObjectSqlListReportPrint(List<Object> objectSqlListReportPrint) {
this.objectSqlListReportPrint = objectSqlListReportPrint;
}
sorry before, if my english is to bad, but I hope you understand about what I mean...
thanks before...
I'm populating an array by taking data from a mysql table, and what I'm trying to do is iterate through that array, check the value of each item and then do perform different actions depending on what the value is.
This is the code for the method where I connect to the database and try and iterate through the array
public void HomeRecord(){
ArrayList<HomeTeamResults> allResults = new ArrayList<>();
try
{
//Sets up the connedtion to the database and installs drivers which are required.
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost", "username", "password");
String table = box1.getSelectedItem().toString();
String SQL = "SELECT * FROM " + table + " WHERE `HomeTeam` = ?";
PreparedStatement prepst;
prepst = con.prepareStatement(SQL);
prepst.setString(1,box1.getSelectedItem().toString());
rs = prepst.executeQuery();
HomeTeamResults hometeamResults=null;
while (rs.next())
{
hometeam = rs.getString("HomeTeam");
awayteam = rs.getString("AwayTeam");
result = rs.getString("Result");
custs = (hometeam + "," + awayteam + "," + result);
allResults.add(hometeamResults);
}
}
catch (Exception e)
{
System.out.println("Error " +e);
}
System.out.println("Size of HomeArrayList::"+allResults.size());
for(HomeTeamResults temp:allResults){
if(temp.getResult().equals("W")){
hometeamvalue = hometeamvalue + 50;
}
else if(temp.getResult().equals("D")){
hometeamvalue = hometeamvalue + 10;
}
else
{
hometeamvalue = hometeamvalue + 0;
}
}
}
And this is the code for the array
public class HomeTeamResults {
private String hometeam;
private String awayteam;
private String result;
public String getHomeTeam() {
return hometeam;
}
public void setHomeTeam(String hometeam) {
this.hometeam = hometeam;
}
public String getAwayTeam() {
return awayteam;
}
public void setAwayTeam(String awayteam) {
this.awayteam = awayteam;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
private HomeTeamResults(String hometeam, String awayteam, String result)
{
this.hometeam = hometeam;
this.awayteam = awayteam;
this.result = result;
}
#Override
public String toString()
{
return " "+hometeam+", "+awayteam+", "+result;
}
}
The problem I have is with the comparison. When I try if(temp.getResult().equals("W") then it doesn't work at all. And if I try if(result.equals("W") then what it does is take the first result from the array and then assumes that every other item in the array is the same.
Not sure where I'm going wrong, any ideas?
You are adding the object in the list but not initialize the object anywhere while iterating the result.
HomeTeamResults hometeamResults=null; // Object is null
while (rs.next())
{
hometeam = rs.getString("HomeTeam");
awayteam = rs.getString("AwayTeam");
result = rs.getString("Result");
custs = (hometeam + "," + awayteam + "," + result); // No idea abt usage
hometeamResults = new HomeTeamResults(hometeam,awayteam,result); // Initial It
allResults.add(hometeamResults); // Now List will contain proper object
}
You are initiallizing the reference with null value what you have to do first is to create your object then set the values in it somewhat like
HomeTeamResults hometeamResults= null;
while (rs.next())
{ hometeamResults=new HomeTeamResults()
hometeam = rs.getString("HomeTeam");
awayteam = rs.getString("AwayTeam");
result = rs.getString("Result");
hometeamResults.setHomeTeam(hometeam);
hometeamResults.setAwayTeam(awayteam);
hometeamResults.setResult(result);
allResults.add(hometeamResults);
}
I am fetching data from a excel sheet containing more than 3000 lines. But I am getting an exception like java.lang.IllegalArgumentException: The supplied POIFSFileSystem contained neither a 'Workbook' entry, nor a 'WORKBOOK' entry. Is it really an excel file?
Below is mine code-
public ActionForward exportExtraExcel(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println("inside exportExtraExcel----------> ");
// String fileName=request.getParameter("filePath");
// System.out.println("fileName----qqqqqqqqqqqqqq---->"+fileName);
String fileName = "C:\\Users\\apanigrahi\\Desktop\\tt.xls";
Statement st = null;
ResultSet rs = null;
EmployeeDTO employeeDTO = new EmployeeDTO();
List cellDataList = new ArrayList();
try {
FileInputStream fileInputStream = new FileInputStream(fileName);
POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream);
HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);
HSSFSheet hssfSheet = workBook.getSheetAt(0);
int rows = hssfSheet.getLastRowNum() + 1;
int col = -1;
for (int i = 0; i < rows; i++) {
HSSFRow hssfRow = hssfSheet.getRow(i);
if (i == 0)
col = hssfRow.getLastCellNum();
List cellTempList = new ArrayList();
for (int j = 0; j < col; j++) {
HSSFCell hssfCell = hssfRow.getCell((short) j);
cellTempList.add(hssfCell);
}
cellDataList.add(cellTempList);
}
} catch (Exception e)
{
e.printStackTrace();
}
List<Integer> empIdArr = new ArrayList<Integer>();
List<Integer> userIdArr = new ArrayList<Integer>();
List<String> empFnameArr = new ArrayList<String>();
List<String> empLnameArr = new ArrayList<String>();
List<String> employeeIdArr = new ArrayList<String>();
List<String> date1 = new ArrayList<String>();
ArrayList<ArrayList> biometric_Data = getBiometricData(cellDataList);
ArrayList<String> date_biometric_Data = biometric_Data.get(0);
ArrayList<String> emp_code_biometric_Data = biometric_Data.get(1);
ArrayList<String> working_hours_biometric_Data = biometric_Data.get(2);
ArrayList<String> date_biometric_Data1 = new ArrayList<String>();
ArrayList<String> emp_code_biometric_Data1 =new ArrayList<String>();
ArrayList<String> working_hours_biometric_Data1 = new ArrayList<String>();
List<EmployeeDTO> extra_empLeaveSummaryReport = new ArrayList<EmployeeDTO>();
try {
connMgr = InitServlet.connMgr;
conn = connMgr.getConnection("access");
st = conn.createStatement();
for (int j = 0; j < emp_code_biometric_Data.size(); j++)
{
String qry = "select emp_id,user_id,emp_first_name,emp_last_name,employee_id from \"Employee\" where employee_id='"
+ emp_code_biometric_Data.get(j)
+ "' and is_deleted is null and emp_current_country ='1' order by employee_id";
rs = st.executeQuery(qry);
if(rs!=null){
while (rs.next()) {
int empId = rs.getInt(1);
empIdArr.add(empId);
userIdArr.add(rs.getInt(2));
empFnameArr.add(rs.getString(3));
empLnameArr.add(rs.getString(4));
employeeIdArr.add(rs.getString(5));
date_biometric_Data1.add(date_biometric_Data.get(j));
emp_code_biometric_Data1.add(emp_code_biometric_Data.get(j));
working_hours_biometric_Data1.add(working_hours_biometric_Data.get(j));
}
}
connMgr.freeConnection("access", conn);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception in exportExcelLeaveSummary");
} finally {
rs.close();
st.close();
connMgr.freeConnection("access", conn);
}
for (int i = 0; i < employeeIdArr.size(); i++)
{
double hours_worked = Double.parseDouble(working_hours_biometric_Data.get(i));
if (hours_worked < 9.00 && hours_worked > 0.0)
{
String day_status = "Halfday";
try {
System.out.println("Inside if loop Halfday");
UserManager userManager = new UserManagerImpl();
employeeDTO = userManager.getEmployeeLeaveDetails(userIdArr.get(i));
employeeDTO.setDate(date_biometric_Data1.get(i));
employeeDTO.setEmployeeId(employeeIdArr.get(i));
employeeDTO.setFirstName(empFnameArr.get(i));
employeeDTO.setLastName(empLnameArr.get(i));
employeeDTO.setWorking_hours(working_hours_biometric_Data1.get(i));
int totalLeaves = employeeDTO.getTotalLeaves();
employeeDTO.setTotalLeaves(totalLeaves);
int plToCredit = employeeDTO.getPlToCredit();
employeeDTO.setPlToCredit(plToCredit);
int slclToCredit = employeeDTO.getSlclToCredit();
employeeDTO.setSlclToCredit(slclToCredit);
int slclTotalBal = totalLeaves - plToCredit;
employeeDTO.setSlclTotalBal(slclTotalBal);
connMgr = InitServlet.connMgr;
conn = connMgr.getConnection("access");
st = conn.createStatement();
String qry = "";
qry = "Select * from \"Est_Employee_Leave_Application\" Where leave_approval_status='Approved' and '"+ ConvertDate.stringtoSQLDate(date_biometric_Data
.get(i))
+ "' between leave_application_from_date and leave_application_to_date And emp_id ='"
+ empIdArr.get(i) + "'";
rs = st.executeQuery(qry);
if (!(rs.equals(null))) {
employeeDTO.setDay_status(day_status);
extra_empLeaveSummaryReport.add(employeeDTO);
request.setAttribute("leaveSummary",extra_empLeaveSummaryReport);
}
} catch (Exception e) {
e.printStackTrace();
System.out
.println("Exception in leaveDetailsReport method");
} finally {
rs.close();
st.close();
connMgr.freeConnection("access", conn);
}
}
if (hours_worked == 0.0) {
String day_status = "LOP";
try {
System.out.println("Inside if loop LOP");
UserManager userManager = new UserManagerImpl();
employeeDTO = userManager.getEmployeeLeaveDetails(userIdArr.get(i));
employeeDTO.setDate(date_biometric_Data1.get(i));
employeeDTO.setEmployeeId(employeeIdArr.get(i));
employeeDTO.setFirstName(empFnameArr.get(i));
employeeDTO.setLastName(empLnameArr.get(i));
employeeDTO.setWorking_hours(working_hours_biometric_Data1.get(i));
int totalLeaves = employeeDTO.getTotalLeaves();
employeeDTO.setTotalLeaves(totalLeaves);
int plToCredit = employeeDTO.getPlToCredit();
employeeDTO.setPlToCredit(plToCredit);
int slclToCredit = employeeDTO.getSlclToCredit();
employeeDTO.setSlclToCredit(slclToCredit);
int slclTotalBal = totalLeaves - plToCredit;
employeeDTO.setSlclTotalBal(slclTotalBal);
connMgr = InitServlet.connMgr;
conn = connMgr.getConnection("access");
st = conn.createStatement();
String qry = "";
qry = "Select * from \"Est_Employee_Leave_Application\" Where '"
+ ConvertDate.stringtoSQLDate(date_biometric_Data
.get(i))
+ "' between leave_application_from_date and leave_application_to_date And emp_id ='"
+ empIdArr.get(i) + "'";
rs = st.executeQuery(qry);
if (!(rs.equals(null))) {
employeeDTO.setDay_status(day_status);
extra_empLeaveSummaryReport.add(employeeDTO);
request.setAttribute("leaveSummary",
extra_empLeaveSummaryReport);
}
} catch (Exception e) {
e.printStackTrace();
System.out
.println("Exception in leaveDetailsReport method");
} finally {
rs.close();
st.close();
connMgr.freeConnection("access", conn);
}
}
}
List<String> columnName = new ArrayList<String>();
columnName.add("Date");
columnName.add("Emp_Id");
columnName.add("Emp_First_Name");
columnName.add("Emp_Last_Name");
columnName.add("SL/CL_TotalBal");
columnName.add("PL_ToCredit");
columnName.add("Total_Leaves");
columnName.add("SL/CL_ToCredit");
columnName.add("Working_Hours");
columnName.add("Day_status");
request.setAttribute("columnNames", columnName);
return mapping.findForward("EXTRA_DETAILED_REPORT");
}
#SuppressWarnings("rawtypes")
public ArrayList<ArrayList> getBiometricData(List cellDataList)
{
EmployeeDTO employeeDTO = new EmployeeDTO();
ArrayList<String> date_Biometric = new ArrayList<String>();
ArrayList<String> emp_code_Biometric = new ArrayList<String>();
ArrayList<String> working_hours_Biometric = new ArrayList<String>();
ArrayList<ArrayList> biometric_All = new ArrayList<ArrayList>();
for (int i = 2; i < cellDataList.size(); i++)
{
List cellTempList = (List) cellDataList.get(i);
for (int j = 0; j < cellTempList.size(); j++)
{
if (j == 0)
{
HSSFCell hssfCell = (HSSFCell) cellTempList.get(0);
Date d1 = hssfCell.getDateCellValue();
SimpleDateFormat sdfAct = new SimpleDateFormat("dd-MMM-YYYY");
String d2 = new SimpleDateFormat("EEEE").format(d1);
String week_day1 = "Sunday";
String week_day2 = "Saturday";
if (week_day1.equals(d2) || week_day2.equals(d2)) {
j = 15;
}
else {
employeeDTO.setDate(sdfAct.format(d1).toString());
}
}
if (j == 1) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(1);
// blank = hssfCell.toString();
// if(blank == "")
// System.out.println("N/A");
// //else
// //System.out.println(blank);
}
if (j == 2) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(2);
String emp_code1 = hssfCell.toString();
String temp = emp_code1;
String non_emp1="10003";
String non_emp2="1001";
String non_emp3="1002";
String non_emp4="1111";
String non_emp5="237";
String non_emp6="002";
String non_emp7="023";
String non_emp8="511";
if(temp.length()>3){
temp = ""+ Integer.parseInt(temp);
}
if(temp.equals(non_emp1)||temp.equals(non_emp2)||temp.equals(non_emp3)||temp.equals(non_emp4)||temp.equals(non_emp5)||temp.equals(non_emp6)||temp.equals(non_emp7)||temp.equals(non_emp8))
{
j=15;
}
else{
String emp_code = "EST" +temp;
employeeDTO.setEmp_code(emp_code);
System.out.println(emp_code);
}
}
if (j == 3) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(3);
String emp_name = hssfCell.toString();
employeeDTO.setName(emp_name);
}
if (j == 4) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(4);
// System.out.println(card_num);
}
if (j == 5) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(5);
String shift_start = hssfCell.toString();
}
if (j == 6) {
String emp_in = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(6);
try {
emp_in = hssfCell.toString();
} catch (Exception e) {
emp_in = "";
}
if (emp_in == "" || emp_in.isEmpty() || emp_in == null) {
} else {
}
}
if (j == 7) {
String emp_out = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(7);
try {
emp_out = hssfCell.toString();
} catch (Exception e) {
}
if (emp_out == "" || emp_out.isEmpty() || emp_out == null) {
} else {
}
}
if (j == 8) {
String shift_end = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(8);
}
if (j == 9) {
String status = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(9);
status = hssfCell.toString();
String holiday_status="Hol";
if(status.equals(holiday_status))
{
j=15;
}
}
if (j == 10) {
String emp_late = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(10);
try {
emp_late = hssfCell.toString();
} catch (Exception e) {
emp_late = "";
}
if (emp_late == "" || emp_late.isEmpty()
|| emp_late == null) {
} else {
}
}
if (j == 11) {
String emp_early = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(11);
try {
emp_early = hssfCell.toString();
} catch (Exception e) {
emp_early = "";
}
if (emp_early == "" || emp_early.isEmpty()
|| emp_early == null) {
} else {
}
}
if (j == 12) {
String hours_worked = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(12);
try {
hours_worked = hssfCell.toString();
employeeDTO.setHours_worked(hours_worked);
} catch (Exception e) {
hours_worked = "";
}
if (hours_worked == "" || hours_worked.isEmpty()|| hours_worked == null)
{
hours_worked = "0.00";
employeeDTO.setHours_worked(hours_worked);
}
date_Biometric.add(employeeDTO.getDate());
emp_code_Biometric.add(employeeDTO.getEmp_code());
working_hours_Biometric.add(employeeDTO.getHours_worked());
}
if (j == 13) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(13);
}
if (j == 14) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(14);
}
}
}
biometric_All.add(date_Biometric);
biometric_All.add(emp_code_Biometric);
biometric_All.add(working_hours_Biometric);
return biometric_All;
}
..................
In the above code I am geting the above mentioned exception in line
HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);