Simply Create Excel Spreadsheets in PHP
In PHP , create excel Spreadsheets of database data we only need to set headers.
header("Content-Type: application/vnd.ms-excel");
and
header("Content-disposition: attachment; filename=city.xls");
The First header we need to set content type ms-excel .
The Second header will make file downloadable. when we run this file into browser then browser will ask to download xls file.
Example 1
echo 'Name' . "\t" . 'Address' . "\t" . 'Contact' . "\n";
echo 'Coderain' . "\t" . 'Internet' . "\t" . '111111111' . "\n";
Explaination
Example 1 will add Name , Address , Contact column into excel as a header of excel file. then you can add data after this.
\t = \t is used for end current tab or column and go to the next tab or column.
\n = \n is used for go to next Row or Line.
Here is the complete example of create excel file of mysql data with PHP
<?phpSo this is the simplest tutorial to create excel spreadsheet with PHP without using any library
ob_start();
header("Content-Type: application/vnd.ms-excel");
$servername = "localhost";
$username = "root";
$password = "";
$db = "statecity";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$querydata = "select * from states where country_id='101'";
$getState = mysqli_query($conn , $querydata);
while($row = mysqli_fetch_assoc($getState))
{
$getStateName = $row['name'];
echo "State Name is $getStateName"."\n";
}
header("Content-disposition: attachment; filename=states.xls");
?>
Comments
Post a Comment