Latest Post
Tampilkan postingan dengan label Excel. Tampilkan semua postingan
Tampilkan postingan dengan label Excel. Tampilkan semua postingan

Reading Excel Documents with PHP, Ajax and jQuery

Written By Unknown on Selasa, 01 Mei 2012 | 08.16

Every wanted to display information from an excel document on a website? Ever wanted to do it asynchronously? Today is your lucky day. This article will show you how to load in an excel document using php, jquery and ajax.


To read more about this article Click Here

For Demo Click Here



Export MYSQL data into Excel/CSV via php

Written By Unknown on Rabu, 30 November 2011 | 08.56

Today i came across a functionality where i need to Export the MYSQL data into CSV/Excel file via PHP function/script. There are such requirement where client needs to Export the MYSQL data (Order data,Member data,Newsletter emails etc) into Excel sheet or CSV file for future reference or need to send to other team for future work.


You can give a button or link from where client can click on it and get a Excel or CSV file with all data from MYSQL database tables using(through) PHP.

Here i am sharing a function using which you can easily export the MYSQL data into Excel/CSV with a single click on button or link. If you are looking to export the filtered data than you can pass parameters into function and make a sql query accordingly. Do you know how to Import CSV/Excel data into MYSQL ?

<?php
function export_excel_csv()
{
    $conn = mysql_connect("localhost","root","");
    $db = mysql_select_db("database",$conn);
    $sql = "SELECT * FROM table";
    $rec = mysql_query($sql) or die (mysql_error());
    $num_fields = mysql_num_fields($rec);
    for($i = 0; $i < $num_fields; $i++ )
    {
        $header .= mysql_field_name($rec,$i)."\\t";
    }
    while($row = mysql_fetch_row($rec))
    {
        $line = '';
        foreach($row as $value)
        {                                            
            if((!isset($value)) || ($value == ""))
            {
                $value = "\\t";
            }
            else
            {
                $value = str_replace( '"' , '""' , $value );
                $value = '"' . $value . '"' . "\\t";
            }
            $line .= $value;
        }
        $data .= trim( $line ) . "\\n";
    }
    $data = str_replace("\\r" , "" , $data);
    if ($data == "")
    {
        $data = "\\n No Record Found!\n";                        
    }
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=reports.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    print "$header\\n$data";
}
?>

What you need to do is…
1) Copy above function and paste it into your file.
2) Change MYSQL connection settings in mysql_connect("localhost","root","").
3) Change database name in mysql_select_db("database",$conn)
4) Change table name in $sql = "SELECT * FROM table".
5) Thats it.

Let me know your thoughts for the same. If you face any problem in this than let me know via comment

Import CSV/Excel data into MYSQL database via PHP

Written By Unknown on Minggu, 27 November 2011 | 09.01


Today i came across a functionality where i need to import the CSV/Excel file in to MYSQL database via PHP script. There is a special requirement from client where he can upload the CSV/Excel file in file upload field in HTML form and all data from CSV/Excel must import into MYSQL database table through PHP.

You can import data of CSV/Excel into MYSQL via PHP using fgetcsv() function along with some file handling functions. Here i would like to share that script with all of you. I hope that in future this article will be helpful to you when you need to implement this type of functionality.



if(isset($_POST['SUBMIT']))
{
     $fname = $_FILES['sel_file']['name'];
     $chk_ext = explode(".",$fname);
     if(strtolower($chk_ext[1]) == "csv")
     {
         $filename = $_FILES['sel_file']['tmp_name'];
         $handle = fopen($filename, "r");
         while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
         {
            $sql = "INSERT into user(name,email,phone) values('$data[0]','$data[1]','$data[2]')";
            mysql_query($sql) or die(mysql_error());
         }
         fclose($handle);
         echo "Successfully Imported";
     }
     else
     {
         echo "Invalid File";
     }    
}
<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post'>
    Import File : <input type='text' name='sel_file' size='20'>
    <input type='submit' name='submit' value='submit'>
</form>


Above code will first check for valid csv file. If it is valid csv file than with the use of fopen() function , uploaded file will be opened in read mode. Now using fgetcsv() function , you will have a line by line data from csv file. 

Each line you will get is an array with all column values.  So now you have all data from csv file. You can play with them according to your needs. I have shown an example to insert 3 data in database table user. If your csv file contains more data than you will get in $data[0] , $data[1], $data[2],$data[3] and so on..

Thats it. Let me know your thoughts for the same. If you face any problem in this than let me know via comment

Reading Excel Documents from PHP applications

Written By Unknown on Senin, 24 Mei 2010 | 22.29


In this article we will learn on how we can read Microsoft Excel Sheet in PHP. To achieve this we will be using Open Source Tool PHPExcelReader. It provides us with necessary API that allow us to read the Excel Sheet in PHP.


Directory Structure for ExcelReader:
When you will unzip the excelreader, you will find example.php that shows us how to read excel sheet using php code. And the most important thing is the Excel folder, it contains all the necessary files and API that will actually perform your operation. Keep the Excel folder as it is as files are included in the API code as per the directory structure.

Example:
Well the included example.php is sufficient to understand the functionality of the ExcelReader. But i am showing the same code here with slight modification.

< ?php
 
require_once 'Excel/reader.php';
$data = new Spreadsheet_Excel_Reader();
 
// Set output Encoding.
$data->setOutputEncoding('CP1251');
 
/***
* if you want you can change 'iconv' to mb_convert_encoding:
* $data->setUTFEncoder('mb'); *
** /
 /***
* By default rows & cols indeces start with 1
* For change initial index use:
*/
* $data->setRowColOffset(0); *
*
 
/***
* Some function for formatting output.
* $data->setDefaultFormat('%.2f');
columns with unknown formatting * * $data->setColumnFormat(4, '%.3
* setDefaultFormat - set format fo rf'); * setColumnFormat - set format for column (apply only to number fields) *
** /
 $data->read('test.xls'); //Passing the excel sheet to be read from PHP
error_reporting(E_ALL ^ E_NOTICE);
 
for ($i = 0; $i < = $data->sheets[0]['numRows']; $i++) {
echo $data->sheets[0]['cells'][$i][1]."<br />";
}
 
?>
 
 
The most important thing here is:
DescriptionSource Code
Accessing Specific Sheet object inside excel document$data->sheets[0](Accessing 1st sheet)
Accessing total rows inside specific sheet$data->sheets[0]['numRows']
Accessing individual cells data$data->sheets[0]['cells'][0][1] (Here i am accessing 1st sheet cell[0][1] i.e. A1 cell)
If we know this basic code than we can read the data inside the excel sheet from php.

Creating Word, Excel and CSV files with PHP

Written By Unknown on Sabtu, 13 Maret 2010 | 00.51


Browsing the World Wide Web you can find out various methods of creating files with PHP. In this article we demonstrate several ways to create Microsoft Word and Excel documents, and also CSV files using PHP.

  • MS Word document
    • Using HTTP headers
    • Using COM objects
    • Using OpenOffice templates
    • Using Zend Framework component phpLiveDocx
  • MS Excel document
    • Using HTTP headers
    • Using COM objects
  • CSV file
    • Using HTTP headers
    • Using fputcsv()
How to create MS Word document
Method 1 - Using HTTP headers
In this method you need to format the HTML/PHP page using Word-friendly CSS and add header information to your PHP script. Make sure you don't use external style sheets since everything should be in the same file.
As a result user will be prompted to download a file. This file will not be 100% "original" Word document, but it certainly will open in MS Word application. You can use this method both for Unix and Windows environments.
<?php
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=document_name.doc");

echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<b>My first document</b>";
echo "</body>";
echo "</html>";
?>
As you may note, the formatting capabilities are limited here.

Method 2 - Using COM objects
Note that the server running the code stated below must have MS Word installed. COM will work on Windows only.
Word document is saved to the temporary directory and then sent to the browser via readfile() function.
...
// Create new COM object – word.application
$word = new COM("word.application");

// Hide MS Word application window
$word->Visible = 0;

//Create new document
$word->Documents->Add();

// Define page margins 
$word->Selection->PageSetup->LeftMargin = '2';
$word->Selection->PageSetup->RightMargin = '2';

// Define font settings
$word->Selection->Font->Name = 'Arial';
$word->Selection->Font->Size = 10;

// Add text
$word->Selection->TypeText("TEXT!");

// Save document
$filename = tempnam(sys_get_temp_dir(), "word");
$word->Documents[1]->SaveAs($filename);

// Close and quit
$word->quit();
unset($word);

header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=document_name.doc");

// Send file to browser
readfile($filename);
unlink($filename);
...

Method 3 - Using OpenOffice templates
  1. Create manually an ODT template with placeholders, like [%value-to-replace%].
  2. When instantiating the template with real data in PHP, unzip the template ODT (it's a zipped XML), and run against the XML the textual replace of the placeholders with the actual values.
  3. Zip the ODT back.
  4. Run the conversion ODT -> DOC via OpenOffice command line interface.
There are tools and libraries available to ease each of those steps.
Method 4 - Using Zend Framework component phpLiveDocx
One of the ways to create DOC files in Linux using PHP is to use the Zend Framework component phpLiveDocx. It allows developers to generate documents by combining structured data from PHP with a template, created in a word processor. The resulting document can be saved as a PDF, DOCX, DOC or RTF file. The concept is the same as with mail-merge.
PhpLiveDocx is completely free to download and use. For more information, please take a look athttp://www.phplivedocx.org/articles/brief-introduction-to-phplivedocx/.


How to create MS Excel document

Method 1 - Using HTTP headers
As described for the MS Word, you need to format the HTML/PHP page using Excel-friendly CSS and add header information to your PHP script.
<?php
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment;Filename=document_name.xls");

echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<b>testdata1</b> \t <u>testdata2</u> \t \n ";
echo "</body>";
echo "</html>";
?>

Method 2 - Using COM objects
Note that the server running the code stated below must have MS Excel installed.
We use the same approach as for MS Word with saving a file to the temporary directory first.
...
//Create new COM object – excel.application
$xl = new COM("excel.application");

//Hide MS Excel application window
$xl->Visible = 0;

//Create new document
$xlBook = $xl->Workbooks->Add();

//Create Sheet 1
$xlBook->Worksheets(1)->Name = "Worksheet 1";
$xlBook->Worksheets(1)->Select;

//Set Width & Height
$xl->ActiveSheet->Range("A1:A1")->ColumnWidth = 10.0;
$xl->ActiveSheet->Range("B1:B1")->ColumnWidth = 13.0;

//Add text
$xl->ActiveSheet->Cells(1,1)->Value = "TEXT";
$xl->ActiveSheet->Cells(1,1)->Font->Bold = True;

//Save document
$filename = tempnam(sys_get_temp_dir(), "excel");
$xlBook->SaveAs($filename);

//Close and quit
unset( $xlBook);
$xl->ActiveWorkBook->Close();
$xl->Quit();
unset( $xl );

header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment;Filename=document_name.xls");

// Send file to browser
readfile($filename);
unlink($filename);
...


How to create a CSV file

Method 1 - Using HTTP headers
As in the examples for the Word and Excel, you need to add header information to your PHP script.
The code snippet below creates a CSV file of the specified table including its column names. Then user will be prompted to download this file.
<?php
$table = 'table_name';
$outstr = NULL;

header("Content-Type: application/csv");
header("Content-Disposition: attachment;Filename=cars-models.csv");

$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("db",$conn);

// Query database to get column names  
$result = mysql_query("show columns from $table",$conn);
// Write column names
while($row = mysql_fetch_array($result)){
    $outstr.= $row['Field'].',';
}  
$outstr = substr($outstr, 0, -1)."\n";

// Query database to get data
$result = mysql_query("select * from $table",$conn);
// Write data rows
while ($row = mysql_fetch_assoc($result)) {
    $outstr.= join(',', $row)."\n";
}

echo $outstr;
mysql_close($conn);
?>

Method 2 - Using fputcsv()
The fputcsv() function formats a line as CSV and writes it to an open file. For more information, take a look at http://php.net/manual/en/function.fputcsv.php.
The code snippet below creates a CSV file of the specified table including its column names and sends it to the browser.
<?php 
$table = 'table_name';
$filename = tempnam(sys_get_temp_dir(), "csv");

$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("db",$conn);

$file = fopen($filename,"w");

// Write column names
$result = mysql_query("show columns from $table",$conn);
for ($i = 0; $i < mysql_num_rows($result); $i++) {
    $colArray[$i] = mysql_fetch_assoc($result);
    $fieldArray[$i] = $colArray[$i]['Field'];
}
fputcsv($file,$fieldArray);

// Write data rows
$result = mysql_query("select * from $table",$conn);
for ($i = 0; $i < mysql_num_rows($result); $i++) {
    $dataArray[$i] = mysql_fetch_assoc($result);
}
foreach ($dataArray as $line) {
    fputcsv($file,$line);
}

fclose($file);

header("Content-Type: application/csv");
header("Content-Disposition: attachment;Filename=cars-models.csv");

// send file to browser
readfile($filename);
unlink($filename);
?>
 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. Kumpulan Kata Broadcast Blackberry - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger