Pages

Tuesday, July 3, 2012

Generate Excel Report with Php and Mysql using code

Step 1. Include phpexcel class file along with your config file and make its object with excel file name passed parameter in constructor. You can check for  error in next line as shown

1require_once("excelwriter.class.php");
2
3$excel=new ExcelWriter("report.xls");
4
5if($excel==false)
6echo $excel->error;


Step 2. Now time to fetch data from mysql database. Before fetch data, call excel header having columns as values of array.

01// this will create heading of each column in excel file
02
03$myArr=array("S.No.","Company Name","Email","City","Username","Reg. Date");
04$excel->writeLine($myArr);
05
06// now fetch data from database table, there is a new line create each time loop runs
07
08$qry=mysql_query("select * from customer");
09if($qry!=false)
10{
11 $i=1;
12 while($res=mysql_fetch_array($qry))
13 {
14 $myArr=array($i,$res['company_name'],$res['email'],...);
15 $excel->writeLine($myArr);
16 $i++;
17 }
18}


Step 3.  Create link to generate excel file.
1<a href="javascript:void(0);" onClick="download();">Download Excel Reporta>
and here download function pointing to excel file
1
 Download Code Here





6 comments:

  1. Hi,

    Thanks For the code . It is working good in firefox and safari.

    but in chrome . It is not showing any downloading functionality. but it is downloading parallel to the php files in the php local server.


    Can you please help me ?

    Thanks,
    Pratap

    ReplyDelete
    Replies
    1. Yes found the glitch...you must be using the same javascript function name as specified in example code...Chrome reserves download as a event for anchor tags and as such it can't be used as a function name... more info from a copied source is here

      http://stackoverflow.com/questions/7852237/cant-use-download-as-a-function-name-in-javascript

      Delete
    2. or here
      http://itfeast.blogspot.in/2012/10/chrome-error-uncought-typeerrorstring.html

      Delete
  2. Never tested on Chrome as client was used to IE will test and come up with fixes asap.If you get any way out do let us know.

    ReplyDelete
  3. Thank You For your Reply .

    I have used the PHPExcel library to get Excel Sheets.

    https://phpexcel.codeplex.com/discussions/269669

    ReplyDelete
  4. thanks your code made my day :)

    ReplyDelete