Friday, 10 April 2015

Export Table To Excel Using Jquery

 HTML
 <table id="tableId"> <tr> <th>Id</th> <th>Name</th> <th>Sal</th> </tr> <tr> <td>1</td> <td>Abc</td> <td>100000</td> </tr> <tr> <td>2</td> <td>Pqr</td> <td>100000</td> </tr> <tr> <td>3</td> <td>Xyz</td> <td>100000</td> </tr> </table>

<input type="button" id="btnExport"  
value=" Export Table data into Excel " /> 
 
JAVA SCRIPT   
 
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js">
</script>
<script src="../src/jquery.table2excel.js"></script>  
 
 $("#btnExport").click(function (e) {
var dt = new Date(); $("#tableId").table2excel({ exclude: ".noExl", name: 'Table'+dt.getDate()+'_'+(dt.getMonth()+1)+'_'+dt.getFullYear() }); 
});
 jquery.table2excel.js

//table2excel.js
;(function ( $, window, document, undefined ) {
  var pluginName = "table2excel",
    defaults = {
    exclude: ".noExl",
                name: "Table2Excel"
  };

  // The actual plugin constructor
  function Plugin ( element, options ) {
    this.element = element;
    // jQuery has an extend method which merges the contents of two or
    // more objects, storing the result in the first object. The first object
    // is generally empty as we don't want to alter the default options for
    // future instances of the plugin
    this.settings = $.extend( {}, defaults, options );
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
  }

  Plugin.prototype = {
   init: function () {
    var e = this;
    e.template = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\"><head><!--[if gte mso 9]><xml>";
    e.template += "<x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions>";
    e.template += "<x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>";
    e.tableRows = "";

    // get contents of table except for exclude
    $(e.element).find("tr").not(this.settings.exclude).each(function (i,o) {
     e.tableRows += "<tr>" + $(o).html() + "</tr>";
    });
    this.tableToExcel(this.tableRows, this.settings.name);
   },
   tableToExcel: function (table, name) {
    var e = this;
    e.uri = "data:application/vnd.ms-excel;base64,";
    e.base64 = function (s) {
     return window.btoa(unescape(encodeURIComponent(s)));
    };
    e.format = function (s, c) {
     return s.replace(/{(\w+)}/g, function (m, p) {
      return c[p];
     });
    };
    e.ctx = {
     worksheet: name || "Worksheet",
     table: table
    };
    window.location.href = e.uri + e.base64(e.format(e.template, e.ctx));
   }
  };

  $.fn[ pluginName ] = function ( options ) {
    this.each(function() {
      if ( !$.data( this, "plugin_" + pluginName ) ) {
        $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
      }
    });

    // chain jQuery functions
    return this;
  };

})( jQuery, window, document );
 

Wednesday, 11 March 2015

MySQL GROUP_CONCAT Function

MySQL GROUP_CONCAT(): Function returns a string with concatenated non-NULL value from a group.

Let’s take a look at the table vehicle_Driver.

We can find each vehicle_number having more than one driver_id.
i.e 1 vehicle contains more than one driver.

Desired Output:

id   vehicle_number    driver_id
1      HR55M6112       2,1,10

Want driver names to be displayed in place of driver_id look at driver_master.


Desired Output

vehicle_number  driver_name

HR55M6112       Abc,Xyz,Pqr

Query

SELECT m.vehicle_number,
(select GROUP_CONCAT(driver_name) from driver_master where driver_id in (select driver_id from vehicle_driver where vehicle_number=m.vehicle_number)) drivers
             FROM vehicle_driver m group by vehicle_number;






Wednesday, 6 August 2014

How to take backup and restore database through commandprompt

It is a good idea to backup your MySQL data occasionally as a precautionary measure. It is also a good idea to create a backup before making any major changes, in-case something goes wrong and you need to revert to the unmodified version. Database backups can also be used to transfer your database from one server to another if you change web hosts.

Open command prompt.



First go to MySQL bin folder.

Take Backup.
mysqldump -u username -ppassword databasename>databasename.sql

Eg:
mysqldump -u root -ppassword Test>c:\Test.sql

If it displays Access is denied.

Run cmd as Administrator

Start->cmd->Right click Run as Administrator.

                                                                     Restore.
mysql -u username -ppassword databasename<databasename.sql

Eg:
mysql -u root -ppassword Test<"c:\Test.sql"




Tuesday, 5 August 2014

Selecting duplicate IDs in mysql

select column_name,count(*) from table_name group by column_name having count(*)>1;

Example:

select consignment_id,count(*) from trip_sheet_trip group by consignment_id having count(*)>1;

Tuesday, 29 July 2014

Hibernate Named Query with Aggregate function

Code for executing Native SQL Query.

Session session = sessionFactory.getCurrentSession();
 
Query query = session.createSQLQuery(
"SELECT sum(hsd_plt_veh) as hsd_plt_veh,sum(randmCost) as randmCost"+
 "from expenses_profit where monthk=:mon and yeark=:yr");
 .setParameter("mon", 1) 
.setParameter("yr", 2014);
 
Object obj=return query.uniqueResult(); 

When we use Native SQL it returns an object.

************************************************************************************************

If we need column names along with the Object use below code.

Session session = sessionFactory.getCurrentSession();
 
Query query = session.createSQLQuery(
"SELECT sum(hsd_plt_veh) as hsd_plt_veh,sum(randmCost) as randmCost"+
 "from expenses_profit where monthk=:mon and yeark=:yr");
.setParameter("mon", 1) 
.setParameter("yr", 2014); 
Map<String, String> expensesProfits =(Map<String, String>) query.uniqueResult();
query.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); 
 
//contains column names and values
List<Map<String,Object>> aliasToValueMapList=query.list(); 
********************************************************************************** 
If we use 
 .addEntity(Cost.class) ;
All checks for all columns in the table in query.
Suppose id is 1st column if we dont mention in query 
It gives following error.
 
ERROR org.hibernate.util.JDBCExceptionReporter - Column 'id' not found. 


 
 
 

Sunday, 27 July 2014

Best open sources java web graph library for drawing graphs on jsp webpage

I have found different API's for graphs in which amCharts uses JavaScript/HTML5 have LIVEEDITOR which supports all browsers so powerfull and have motion-charts which change data at run time by default can export charts as images or PDF files.

JSCharts:

JS Charts is a JavaScript based chart generator that requires little or no coding. With JS Charts drawing charts is a simple and easy task, since you only have to use client-side scripting (i.e. performed by your web browser). No additional plugins or server modules are required. Just include our scripts, prepare your chart data in XML, JSON or JavaScript Array and your chart is ready!



http://www.jscharts.com/free-download

JQPlot :

JqPlot is a plotting and charting plugin for the jQuery Javascript framework. jqPlot produces beautiful line, bar and pie charts with many features:
  • Numerous chart style options.
  • Date axes with customizable formatting.
  • Up to 9 Y axes.
  • Rotated axis text.
  • Automatic trend line computation.
  • Tooltips and data point highlighting.
  • Sensible defaults for ease of use.

   http://www.jqplot.com/

amCharts:

We offer JavaScript/HTML5 charts for most of your needs. The set includes serial (column, bar, line, area, step line, step without risers, smoothed line, candlestick and ohlc graphs), pie/donut, radar/polar, y/scatter/bubble, Funnel/Pyramid charts and Angular Gauges. Our charts offer unmatched functionality and performance in a modern, standards compliant package. Our JS charting library is responsive and supported by touch/mobile devices.


http://www.amcharts.com/javascript-charts/.


Tuesday, 15 July 2014

Silent print of PDF using JAVA.

I have used javax.print API to perform printing of PDF without user interaction.
It is running only in MAC still search is going on for Windows.

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;


public class Abc {
  /**
  * @param args
  */
  public static void main(String[] args) {

    new Abc().print();
  }
  public void print() {
  /*
    The format of Page will be PDF.
    We have different types based on what we pass to printer.
  */
    DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;

   // Number of printers in network will be recognized.

    PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, null);
    FileInputStream psStream = null;  
    try {  
        psStream = new FileInputStream
       ("E:/apache-tomcat-7.0.30/webapps/pdf/TripSheetReport 27-3.pdf");  
        } catch (FileNotFoundException ffne) {  
             ffne.printStackTrace();  
        }  
    if (psStream == null) {  
        return;  
    }       
    if (services.length > 0)
    {
       PrintService myService = null;
       for(PrintService service : services) {
       System.out.println(service.getName());
       // Check whether connected printer is recognized.
          if(service.getName().contains("M1136")) {
            myService = service;
     break;
          }
       }
       DocPrintJob printJob = myService.createPrintJob();
       Doc document = new SimpleDoc(psStream, flavor, null);
       
       try {
 
         // Sends the document to print.
  printJob.print(document, new HashPrintRequestAttributeSet());
     } catch (PrintException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
      }
 }
  else
  {
     System.out.println("No PDF printer available.");
  }       
 }
        // To check the status of Print.

   class PrintJobWatcher {
      boolean done = false;
      PrintJobWatcher(DocPrintJob job) {
         job.addPrintJobListener(new PrintJobAdapter() {
       public void printJobCanceled(PrintJobEvent pje) {
          allDone();
       }
       public void printJobCompleted(PrintJobEvent pje) {
         allDone();
       }
       public void printJobFailed(PrintJobEvent pje) {
         allDone();
       }
       public void printJobNoMoreEvents(PrintJobEvent pje) {
         allDone();
       }
       void allDone() {
         synchronized (PrintJobWatcher.this) {
           done = true;
           System.out.println("Printing done ...");
           PrintJobWatcher.this.notify();
         }
       }
   });
 }
   
}
}