Exporting mysql to excel php

I’m trying to get my MySQL data to Excel file, but I’m having problems with Excel cells. All my text goes to one cell, I would like to have each row value in separate Excel cell. Here is my code:

$queryexport = ("
SELECT username,password,fullname FROM ecustomer_users
WHERE fk_customer='".$fk_customer."'
");

$row = mysql_fetch_assoc($queryexport);

$result = mysql_query($queryexport);
$header = '';

for ($i = 0; $i < $count; $i++){
   $header .= mysql_field_name($result, $i)."t";
   }

while($row = mysql_fetch_row($result)){
   $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 = "nno matching records foundn";
   }
}
header("Content-type: application/vnd.ms-excel; name='excel'");
header("Content-Disposition: attachment; filename=exportfile.xls");
header("Pragma: no-cache");
header("Expires: 0");

// output data
echo $header."n".$data;

mysql_close($conn);`

Naresh's user avatar

Naresh

2,73110 gold badges45 silver badges78 bronze badges

asked Mar 29, 2013 at 7:40

marc_s's user avatar

3

Just Try With The Following :

PHP Part :

<?php
/*******EDIT LINES 3-8*******/
$DB_Server = "localhost"; //MySQL Server    
$DB_Username = "username"; //MySQL Username     
$DB_Password = "password";             //MySQL Password     
$DB_DBName = "databasename";         //MySQL Database Name  
$DB_TBLName = "tablename"; //MySQL Table Name   
$filename = "excelfilename";         //File Name
/*******YOU DO NOT NEED TO EDIT ANYTHING BELOW THIS LINE*******/    
//create MySQL connection   
$sql = "Select * from $DB_TBLName";
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database   
$Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());   
//execute query 
$result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());    
$file_ending = "xls";
//header info for browser
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename.xls");  
header("Pragma: no-cache"); 
header("Expires: 0");
/*******Start of Formatting for Excel*******/   
//define separator (defines columns in excel & tabs in word)
$sep = "t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "t";
}
print("n");    
//end of printing column names  
//start while loop to get data
    while($row = mysql_fetch_row($result))
    {
        $schema_insert = "";
        for($j=0; $j<mysql_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/rn|nr|n|r/", " ", $schema_insert);
        $schema_insert .= "t";
        print(trim($schema_insert));
        print "n";
    }   
?>

I think this may help you to resolve your problem.

answered Mar 29, 2013 at 9:06

John Peter's user avatar

John PeterJohn Peter

2,8703 gold badges26 silver badges45 bronze badges

13

Try this code. It’s definitly working.

<?php
// Connection 

$conn=mysql_connect('localhost','root','');
$db=mysql_select_db('excel',$conn);

$filename = "Webinfopen.xls"; // File Name
// Download file
header("Content-Disposition: attachment; filename="$filename"");
header("Content-Type: application/vnd.ms-excel");
$user_query = mysql_query('select name,work from info');
// Write data to file
$flag = false;
while ($row = mysql_fetch_assoc($user_query)) {
    if (!$flag) {
        // display field/column names as first row
        echo implode("t", array_keys($row)) . "rn";
        $flag = true;
    }
    echo implode("t", array_values($row)) . "rn";
}
?>

answered Nov 18, 2014 at 5:38

Dileep kurahe's user avatar

5

If you just want your query data dumped into excel I have to do this frequently and using an html table is a very simple method. I use mysqli for db queries and the following code for exports to excel:

header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=filename.xls");  
header("Pragma: no-cache"); 
header("Expires: 0");


echo '<table border="1">';
//make the column headers what you want in whatever order you want
echo '<tr><th>Field Name 1</th><th>Field Name 2</th><th>Field Name 3</th></tr>';
//loop the query data to the table in same order as the headers
while ($row = mysqli_fetch_assoc($result)){
    echo "<tr><td>".$row['field1']."</td><td>".$row['field2']."</td><td>".$row['field3']."</td></tr>";
}
echo '</table>';

answered Jan 27, 2017 at 16:42

RLytle's user avatar

RLytleRLytle

1211 silver badge5 bronze badges

2

This is new version of php code

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_dbname";
//mysql and db connection

$con = new mysqli($servername, $username, $password, $dbname);

if ($con->connect_error) {  //error check
    die("Connection failed: " . $con->connect_error);
}
else
{

}


$DB_TBLName = "your_table_name"; 
$filename = "excelfilename";  //your_file_name
$file_ending = "xls";   //file_extention

header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename.'.'.$file_ending");  
header("Pragma: no-cache"); 
header("Expires: 0");

$sep = "t";

$sql="SELECT * FROM $DB_TBLName"; 
$resultt = $con->query($sql);
while ($property = mysqli_fetch_field($resultt)) { //fetch table field name
    echo $property->name."t";
}

print("n");    

while($row = mysqli_fetch_row($resultt))  //fetch_table_data
{
    $schema_insert = "";
    for($j=0; $j< mysqli_num_fields($resultt);$j++)
    {
        if(!isset($row[$j]))
            $schema_insert .= "NULL".$sep;
        elseif ($row[$j] != "")
            $schema_insert .= "$row[$j]".$sep;
        else
            $schema_insert .= "".$sep;
    }
    $schema_insert = str_replace($sep."$", "", $schema_insert);
    $schema_insert = preg_replace("/rn|nr|n|r/", " ", $schema_insert);
    $schema_insert .= "t";
    print(trim($schema_insert));
    print "n";
}

answered Apr 11, 2017 at 6:31

A.A Noman's user avatar

A.A NomanA.A Noman

5,2069 gold badges26 silver badges46 bronze badges

1

I think you should try with this API

http://code.google.com/p/php-excel/source/browse/trunk/php-excel.class.php

With This

Create a quick export from a database table into Excel

Compile some statistical records with a few calculations and deliver
the result in an Excel worksheet

Gather the items off your (web-based) todo list, put them in a
worksheet and use it as a foundation for some more statistics
magic.**

answered Mar 29, 2013 at 8:05

Naresh's user avatar

NareshNaresh

2,73110 gold badges45 silver badges78 bronze badges

Try this code:

<?php
    header("Content-type: application/vnd-ms-excel");

    header("Content-Disposition: attachment; filename=hasil-export.xls");

    include 'view-lap.php';
?>

Spooky's user avatar

Spooky

2,9668 gold badges27 silver badges41 bronze badges

answered Oct 31, 2013 at 21:17

Jek Tv's user avatar

0

try this code

data.php

    <table border="1">
<tr>
    <th>NO.</th>
    <th>NAME</th>
    <th>Major</th>
</tr>
<?php
//connection to mysql
mysql_connect("localhost", "root", ""); //server , username , password
mysql_select_db("codelution");

//query get data
$sql = mysql_query("SELECT * FROM student ORDER BY id ASC");
$no = 1;
while($data = mysql_fetch_assoc($sql)){
    echo '
    <tr>
        <td>'.$no.'</td>
        <td>'.$data['name'].'</td>
        <td>'.$data['major'].'</td>
    </tr>
    ';
    $no++;
}
?>

code for excel file

export.php

<?php
// The function header by sending raw excel
header("Content-type: application/vnd-ms-excel");
// Defines the name of the export file "codelution-export.xls"
header("Content-Disposition: attachment; filename=codelution-export.xls");
// Add data table
include 'data.php';
?>

if mysqli version

$sql="SELECT * FROM user_details";
$result=mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0)
{
    $no = 1;
            while($data = mysqli_fetch_assoc($result))
            {echo '
    <tr>
        <<td>'.$no.'</td>
        <td>'.$data['name'].'</td>
        <td>'.$data['major'].'</td>

    </tr>
    ';
    $no++;

http://codelution.com/development/web/easy-ways-to-export-data-from-mysql-to-excel-with-php/

answered Nov 22, 2015 at 16:41

luvking's user avatar

You can export the data from MySQL to Excel by using this simple code.

<?php
include('db_con.php');


$stmt=$db_con->prepare('select * from books');
$stmt->execute();


$columnHeader ='';
$columnHeader = "Sr NO"."t"."Book Name"."t"."Book Author"."t"."Book 
ISBN"."t";


$setData='';

while($rec =$stmt->FETCH(PDO::FETCH_ASSOC))
{
 $rowData = '';
 foreach($rec as $value)
 {
  $value = '"' . $value . '"' . "t";
  $rowData .= $value;
 }
 $setData .= trim($rowData)."n";
}


header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=Book record 
sheet.xls");
header("Pragma: no-cache");
header("Expires: 0");

echo ucwords($columnHeader)."n".$setData."n";

?>

complete code here php export to excel

answered Feb 20, 2018 at 8:46

Ehtesham Shami's user avatar

Posts by John Peter and Dileep kurahe helped me to develop what I consider as being a simpler and cleaner solution, just in case anyone else is still looking. (I am not showing any database code because I actually used a $_SESSION variable.)

The above solutions invariably caused an error upon loading in Excel, about the extension not matching the formatting type. And some of these solutions create a spreadsheet with the data across the page in columns where it would be more traditional to have column headings and list the data down the rows. So here is my simple solution:

$filename = "webreport.csv";
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename");  
header("Pragma: no-cache"); 
header("Expires: 0");
foreach($results as $x => $x_value){
    echo '"'.$x.'",' . '"'.$x_value.'"' . "rn";
}
  1. Change to .csv (which Excel instantly updates to .xls and there is no error upon loading.)
  2. Use the comma as delimiter.
  3. Double quote the Key and Value to escape any commas in the data.
  4. I also prepended column headers to $results so the spreadsheet looked even nicer.

answered Feb 29, 2016 at 23:24

Trialsman's user avatar

TrialsmanTrialsman

3293 silver badges14 bronze badges

Try the Following Code Please.
just only update two values.
1.your_database_name
2.table_name

 <?php
    $host="localhost";
    $username="root";
    $password="";
    $dbname="your_database_name";
    $con = new mysqli($host, $username, $password,$dbname); 

        $sql_data="select * from table_name";
        $result_data=$con->query($sql_data);
        $results=array();
    filename = "Webinfopen.xls"; // File Name
    // Download file
    header("Content-Disposition: attachment; filename="$filename"");
    header("Content-Type: application/vnd.ms-excel");

    $flag = false;
    while ($row = mysqli_fetch_assoc($result_data)) {
        if (!$flag) {
            // display field/column names as first row
            echo implode("t", array_keys($row)) . "rn";
            $flag = true;
        }
        echo implode("t", array_values($row)) . "rn";
    }
    ?>

answered Dec 17, 2016 at 18:22

Samir Lakhani's user avatar

This is baes on John Peter’s answer above. The code is working perfectly but I needed it for WordPress. So, I did something like this:

<?php

require '../../../wp-load.php';

$file_name = "registered-users";
$args = array( 'role' => 'client',
   'meta_query' => array( array(
       'key' => '_dt_transaction_archived',
       'compare' => 'NOT EXISTS'
   ) ),
   'order' => 'DESC',
   'orderby' => 'ID'
);
$users = get_users( $args );
$file_ending = "xls";

// Header info for browser
header( "Content-Type: application/xls" );
header( "Content-Disposition: attachment; filename=$file_name.$file_ending" );
header( "Pragma: no-cache" );
header( "Expires: 0" );

/*******Start of Formatting for Excel*******/

// define separator (defines columns in excel & tabs in word)
$sep = "t"; //tabbed character
// start of printing column names as names of MySQL fields

print( "First Name" . $sep );
print( "Last Name" . $sep );
print( "E-Mail" . $sep );
print( "n" );
// end of printing column names

// start foreach loop to get data
$schema_insert = "";

foreach ($users as $user) {
    if ( $user ) {
        $schema_insert = "$user->first_name" . $sep;
        $schema_insert .= "$user->last_name" . $sep;
        $schema_insert .= "$user->user_email" . $sep;
        print "n";
        $schema_insert = str_replace( $sep . "$", "", $schema_insert );
        $schema_insert = preg_replace( "/rn|nr|n|r/", " ", $schema_insert );
        $schema_insert .= "t";
        print( trim( $schema_insert ) );
    }
}

answered Apr 16, 2021 at 7:16

Dragi Postolovski's user avatar

Recently I published an article How to Read CSV and Excel File in PHP Using PhpSpreadsheet.  One of the readers asked how to use PhpSpreadsheet to export MySQL database records to the Excel file. The user may need their MySQL data in the Excel or CSV file to read or share it easily. In this article, we discussed how one can export data from a database to Excel and CSV files. In addition to this, we will also study how one can send this exported file as an attachment in the email.

Getting Started

For getting started, you first need to install the PhpSpreadsheet library. I recommend using Composer for the installation of the library. Open the terminal in your project root directory and run the command:

composer require phpoffice/phpspreadsheet

PhpSpreadsheet is the library that provides support for reading and writing different types of file formats. Below is the screenshot of supported file formats.

File Supported

Our end goal is exporting database table records to the Excel/CSV file. For this, we require a few entries in our database. As an example, I am creating the ‘products’ table by running the below SQL query.

CREATE TABLE `products` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `product_name` varchar(255) NOT NULL,
 `product_sku` varchar(255) NOT NULL,
 `product_price` varchar(255) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Next, add some dummy entries in the table so you will see a few records in the exported file.

INSERT INTO `products` (`product_name`, `product_sku`, `product_price`) VALUES
('Apple', 'app_111', '$1000'),
('Lenovo', 'len_222', '$999'),
('Samsung', 'sam_689', '$1200'),
('Acer', 'ace_620', '$900');

After this create a config.php file where we write the code for database connection.

config.php

<?php
$db_host = 'DATABASE_HOST';
$db_username = 'DATABASE_USERNAME';
$db_password = 'DATABASE_PASSWORD';
$db_name = 'DATABASE_NAME';
 
$db = new mysqli($db_host, $db_username, $db_password, $db_name);
 
if($db->connect_error){
    die("Unable to connect database: " . $db->connect_error);
}

Make sure to replace the placeholders with the actual values in the above code. This file will be included later to fetch records from the ‘products’ table.

In the next part of the tutorial, I am allocating a separate section for exporting data to Excel, exporting data to CSV, and sending the email with an exported file as an attachment.

Export MySQL Database Data to Excel Using PHP

You have installed the library and also have a database table with few entries. Now you can go ahead and write the actual code which will export an Excel file with data filled in it.

Create a <code>export-to-excel.php</code> file in the root directory. In this file, I will write a SQL query to fetch data from the database, write this data to Excel, and finally send the Excel file to the browser to download automatically.

export-to-excel.php

<?php
require_once "vendor/autoload.php";
require_once "config.php";
 
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;
 
$spreadsheet = new Spreadsheet();
$Excel_writer = new Xlsx($spreadsheet);
 
$spreadsheet->setActiveSheetIndex(0);
$activeSheet = $spreadsheet->getActiveSheet();
 
$activeSheet->setCellValue('A1', 'Product Name');
$activeSheet->setCellValue('B1', 'Product SKU');
$activeSheet->setCellValue('C1', 'Product Price');
 
$query = $db->query("SELECT * FROM products");
 
if($query->num_rows > 0) {
    $i = 2;
    while($row = $query->fetch_assoc()) {
        $activeSheet->setCellValue('A'.$i , $row['product_name']);
        $activeSheet->setCellValue('B'.$i , $row['product_sku']);
        $activeSheet->setCellValue('C'.$i , $row['product_price']);
        $i++;
    }
}
 
$filename = 'products.xlsx';
 
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename='. $filename);
header('Cache-Control: max-age=0');
$Excel_writer->save('php://output');

When you run this code on the browser, an Excel file will be downloaded automatically and the Excel sheet will have the following entries.

Excel

Export MySQL Database Data to CSV Using PHP

In the previous section, we exported data to an Excel file. If someone is looking to export data in a CSV file then you need to change a few lines in the above code.

export-to-csv.php

<?php
require_once "vendor/autoload.php";
require_once "config.php";
 
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterCsv;
 
$spreadsheet = new Spreadsheet();
$Excel_writer = new Csv($spreadsheet);
 
$spreadsheet->setActiveSheetIndex(0);
$activeSheet = $spreadsheet->getActiveSheet();
 
$activeSheet->setCellValue('A1', 'Product Name');
$activeSheet->setCellValue('B1', 'Product SKU');
$activeSheet->setCellValue('C1', 'Product Price');
 
$query = $db->query("SELECT * FROM products");
 
if($query->num_rows > 0) {
    $i = 2;
    while($row = $query->fetch_assoc()) {
        $activeSheet->setCellValue('A'.$i , $row['product_name']);
        $activeSheet->setCellValue('B'.$i , $row['product_sku']);
        $activeSheet->setCellValue('C'.$i , $row['product_price']);
        $i++;
    }
}
 
$filename = 'products.csv';
 
header('Content-Type: application/text-csv');
header('Content-Disposition: attachment;filename='. $filename);
header('Cache-Control: max-age=0');
$Excel_writer->save('php://output');

Send an Email with File as an Attachment

We have seen how to download the file with data in Excel/CSV format. Some users may want to send the exported file as an attachment in the email. Let’s see how to achieve it.

First, install the PHPMailer library using the command:

composer require phpmailer/phpmailer

After installing the library, you can use any SMTP server to send an email. It’s up to you. You may use your hosting SMTP server, AWS SES, or Gmail SMTP server. If you are going with the Gmail SMTP server read our article Send Email Using Gmail SMTP Server from PHP Script which explains the configuration needed for it.

The previous code download Excel/CSV file automatically. But now, instead of making it downloadable, we will save the file in the directory and then send it as an attachment. In short, we will write the code below for saving the file.

...
...
$filename = 'products.csv';
 
if (!file_exists('files')) {
    mkdir('files', 0755);
}
$Excel_writer->save('files/'.$filename);

Our final code to send the attachment in an email will be as follows:

<?php
require_once "vendor/autoload.php";
require_once "config.php";
 
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterCsv;
 
//Import PHPMailer classes into the global namespace
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
 
$spreadsheet = new Spreadsheet();
$Excel_writer = new Csv($spreadsheet);
 
$spreadsheet->setActiveSheetIndex(0);
$activeSheet = $spreadsheet->getActiveSheet();
 
$activeSheet->setCellValue('A1', 'Product Name');
$activeSheet->setCellValue('B1', 'Product SKU');
$activeSheet->setCellValue('C1', 'Product Price');
 
$query = $db->query("SELECT * FROM products");
 
if($query->num_rows > 0) {
    $i = 2;
    while($row = $query->fetch_assoc()) {
        $activeSheet->setCellValue('A'.$i , $row['product_name']);
        $activeSheet->setCellValue('B'.$i , $row['product_sku']);
        $activeSheet->setCellValue('C'.$i , $row['product_price']);
        $i++;
    }
}
 
$filename = 'products.csv';
 
if (!file_exists('files')) {
    mkdir('files', 0755);
}
$Excel_writer->save('files/'.$filename);
 
// send as an attachment
$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host = 'SMTP_HOST';
    $mail->SMTPAuth = true;
    $mail->Username = 'SMTP_USERNAME';   //username
    $mail->Password = 'SMTP_PASSWORD';   //password
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;
 
    $mail->setFrom('FROM_EMAIL_ADDRESS', 'FROM_NAME');
    $mail->addAddress('RECEPIENT_EMAIL_ADDRESS', 'RECEPIENT_NAME');
 
    $mail->addAttachment('files/'.$filename);
 
    $mail->isHTML(true);
    $mail->Subject = 'Products Sheet';
    $mail->Body    = 'Products Sheet';
 
    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: '. $mail->ErrorInfo;
}

Replace the placeholders with the actual values and an email will be sent with an attachment to the recipient’s email address.

I hope you understand how to export MySQL database data to the Excel or CSV file and also send it as an attachment. Please share your thoughts and suggestions in the comment section below.

Related Articles

  • How to Transfer Files to Remote Server in PHP
  • Send Email Using Mailjet in PHP
  • How to Convert HTML to PDF in PHP

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Если нужно быстро и единоразово выгрузить данные из таблицы MySQL в Exel файл, то помогут следующие способы:

1

Экспорт через PHPMyAdmin

В PHPMyAdmin при экспорте можно выбрать формат «CSV for MS Excel»:

Экспорт через PHPMyAdmin

При открытии полученного файла в Excel будет сбита кодировка:

Excel будет сбита кодировка

Чтобы это исправить, нужно открыть csv файл в редакторе типа Notepad++ и изменить кодировку на ANSI:

Notepad++ изменить кодировку на ANSI:

Результат:

2

Экспорт через HTML таблицу

Смысл метода состоит в том чтобы PHP-скриптом сформировать HTML таблицу:

<?php
$dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль');
$sth = $dbh->prepare("SELECT * FROM `test`");
$sth->execute();
$items = $sth->fetchAll(PDO::FETCH_ASSOC);
?>
		
<table>
	<tr>
		<td>ID</td>
		<td>Категория</td>
		<td>Название</td>
		<td>Описание</td>
	</tr>
	<?php foreach($items as $row): ?>
	<tr>
		<td><?php echo $row['id']; ?></td>
		<td><?php echo $row['category']; ?></td>
		<td><?php echo $row['name']; ?></td>
		<td><?php echo $row['text']; ?></td>
	</tr>
	<?php endforeach; ?>
</table>

PHP

Результат работы скрипта:

Полученную таблицу копируем и вставляем в чистый лист Microsoft Exel:

3

Экспорт через PHPExcel

Третий метод – сформировать xls-файл в библиотеке PHPExcel (PHPExcel.zip).

//spl_autoload_unregister('autoload');
require_once __DIR__ . '/PHPExcel/Classes/PHPExcel.php';
require_once __DIR__ . '/PHPExcel/Classes/PHPExcel/Writer/Excel2007.php';

$xls = new PHPExcel();
$xls->setActiveSheetIndex(0);
$sheet = $xls->getActiveSheet();

// Шапка
$sheet->getStyle("A1:D1")->getFont()->setBold(true);
$sheet->setCellValue("A1", 'ID');
$sheet->setCellValue("B1", 'Категория');
$sheet->setCellValue("C1", 'Название');
$sheet->setCellValue("D1", 'Описание');

// Выборка из БД
$dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль');
$sth = $dbh->prepare("SELECT * FROM `test`");
$items = $sth->fetch(PDO::FETCH_ASSOC);

$index = 2;
foreach ($items as $row) {
	$sheet->setCellValue("A" . $index, $row['id']);
	$sheet->setCellValue("B" . $index, $row['category']);
	$sheet->setCellValue("C" . $index, $row['name']);
	$sheet->setCellValue("D" . $index, $row['name']);
	$index++;
}

// Отдача файла в браузер
header("Expires: Mon, 1 Apr 1974 05:00:00 GMT");
header("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/vnd.ms-excel" );
header("Content-Disposition: attachment; filename=prods.xlsx");
 
$objWriter = new PHPExcel_Writer_Excel2007($xls);
$objWriter->save('php://output'); 

exit(); 

PHP

Результат:

This tutorial will learn you How to export Mysql data from web application to Excel file using PHP programming language. This functionality is mostly required in enterprise level web application. There are lots of data are transfer on daily basis and manage that into separate excel file. So, at that time this type of functionality is required in web application. This functionality reduce lots of time to take data into excel file.

In this simple post we have learn something regarding how to export data to Excel in PHP. If you have developed any project then that project you have to required this functionality like Exporting Data to Excel Sheet. So we have developed this tutorial, in which we have make simple PHP Script for Export Data from Web to Excel.

Online Demo

Name Address City Postal Code Country
Maria Anders Obere Str. 57 Berlin 12209 Germany
Ana Trujillo Avda. de la Construction 2222 Mexico D.F. 5021 Mexico
Antonio Moreno Mataderos 2312 Mexico D.F. 5023 Mexico
Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil
Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
Karl Jablonski 305 — 14th Ave. S. Suite 3B Seattle 98128 USA
Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil

Source Code


<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$sql = "SELECT * FROM tbl_customer";  
$result = mysqli_query($connect, $sql);
?>
<html>  
 <head>  
  <title>Export MySQL data to Excel in PHP</title>  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
 </head>  
 <body>  
  <div class="container">  
   <br />  
   <br />  
   <br />  
   <div class="table-responsive">  
    <h2 align="center">Export MySQL data to Excel in PHP</h2><br /> 
    <table class="table table-bordered">
     <tr>  
                         <th>Name</th>  
                         <th>Address</th>  
                         <th>City</th>  
       <th>Postal Code</th>
       <th>Country</th>
                    </tr>
     <?php
     while($row = mysqli_fetch_array($result))  
     {  
        echo '  
       <tr>  
         <td>'.$row["CustomerName"].'</td>  
         <td>'.$row["Address"].'</td>  
         <td>'.$row["City"].'</td>  
         <td>'.$row["PostalCode"].'</td>  
         <td>'.$row["Country"].'</td>
       </tr>  
        ';  
     }
     ?>
    </table>
    <br />
    <form method="post" action="export.php">
     <input type="submit" name="export" class="btn btn-success" value="Export" />
    </form>
   </div>  
  </div>  
 </body>  
</html>

export.php


<?php  
//export.php  
$connect = mysqli_connect("localhost", "root", "", "testing");
$output = '';
if(isset($_POST["export"]))
{
 $query = "SELECT * FROM tbl_customer";
 $result = mysqli_query($connect, $query);
 if(mysqli_num_rows($result) > 0)
 {
  $output .= '
   <table class="table" bordered="1">  
                    <tr>  
                         <th>Name</th>  
                         <th>Address</th>  
                         <th>City</th>  
       <th>Postal Code</th>
       <th>Country</th>
                    </tr>
  ';
  while($row = mysqli_fetch_array($result))
  {
   $output .= '
    <tr>  
                         <td>'.$row["CustomerName"].'</td>  
                         <td>'.$row["Address"].'</td>  
                         <td>'.$row["City"].'</td>  
       <td>'.$row["PostalCode"].'</td>  
       <td>'.$row["Country"].'</td>
                    </tr>
   ';
  }
  $output .= '</table>';
  header('Content-Type: application/xls');
  header('Content-Disposition: attachment; filename=download.xls');
  echo $output;
 }
}
?>

I’ll show you how to export grid data to an excel file in this post. Export/Import is a relatively popular functionality for web development; nevertheless, there are times when we need to export entire grid data into an excel file.

in which case we should use the approach described below. In PHP, we simply need to set header information to force the browser to launch the download window.

Video Tutorial

If you are more comfortable in watching a video that explains about Exporting Data to Excel with PHP and MySQL, then you should watch this video tutorial.

You can also check other tutorial of Export Data with PHP,

  • Exporting Data to Excel with PHP and MySQL
  • Export Data to CSV and Download Using PHP and MySQL
  • Import CSV File Into MySql Using PHP
  • Export HTML Table Data to Excel, CSV, PNG and PDF using jQuery Plugin
  • Export the jQuery Datatable data to PDF,Excel,CSV and Copy

Export MySQL Data To Excel in PHP

Because Excel is the finest format for storing data in a file, exporting data in Excel format is a very important tool that allows users to save data for offline use. You’ll learn how to use PHP and MySQL to export data to Excel.

So the file structure for this example is the following:

  • index.php: This is the entry file.
  • connection.php: This file is used to connect MySQL with PHP
  • generate_excel.php: This is the main PHP file that’ll have an export method to export data into the excel.

Create MySQL Database Table

Let’s create a tasks table that ll all tasks records which will export later on in excel format.

CREATE TABLE `tasks` (
  `id` int(11) NOT NULL,
  `Name` varchar(255) NOT NULL,
  `Status` varchar(255) NOT NULL,
  `Priority` varchar(255) NOT NULL,
  `Date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `tasks`
--
ALTER TABLE `tasks`
  ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for table `tasks`
--
ALTER TABLE `tasks`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
COMMIT;

Now, I’ll insert some sample data into the tasks table.

INSERT INTO `tasks` (`id`, `Name`, `Status`, `Priority`, `Date`) VALUES
(1, 'Task1', 'Completed', 'Low', '2021-09-01'),
(2, 'Task2', 'InProgress', 'High', '2021-03-17'),
(3, 'Mysql', 'Hold', 'Low', '2021-09-22'),
(4, 'API', 'Pending', 'Low', '2021-09-06');

Create MySQL Connection With PHP

We’ll create a connection.php file and add the below code. in this file, We’ll pass the database hostname, database username, database password, and database name.

<?php
Class dbObj{
	/* Database connection start */
	var $dbhost = "localhost";
	var $username = "root";
	var $password = "";
	var $dbname = "test";
	var $conn;
	function getConnstring() {
		$con = mysqli_connect($this->dbhost, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error());

		/* check connection */
		if (mysqli_connect_errno()) {
			printf("Connect failed: %sn", mysqli_connect_error());
			exit();
		} else {
			$this->conn = $con;
		}
		return $this->conn;
	}
}
?>

Get the Tasks Data from MySQL Database Table

We’ll receive entries from a MySQL database table tasks and put them in an array so we can show them and export them to an excel file. Added below code into the top of the generate_excel.php file.

include_once("connection.php");
$db = new dbObj();
$connString =  $db->getConnstring();

$sql_query = "SELECT * FROM tasks";
$resultset = mysqli_query($connString, $sql_query) or die("database error:". mysqli_error($conn));
$tasks = array();
while( $rows = mysqli_fetch_assoc($resultset) ) {
	$tasks[] = $rows;
}

Export Data to Excel

Let’s create export features using PHP and export data into excel. We’ll also force the to browser download the file instead of display it. We’ll add the below code into the generate_excel.php file.

if(isset($_POST["ExportType"]))
{
	 
    switch($_POST["ExportType"])
    {
        case "export-to-excel" :
            // Submission from
			$filename = "phpflow_data_export_".date('Ymd') . ".xls";		 
            header("Content-Type: application/vnd.ms-excel");
			header("Content-Disposition: attachment; filename="$filename"");
			ExportFile($tasks);
			//$_POST["ExportType"] = '';
            exit();
        default :
            die("Unknown action : ".$_POST["action"]);
            break;
    }
}
function ExportFile($records) {
	$heading = false;
		if(!empty($records))
		  foreach($records as $row) {
			if(!$heading) {
			  // display field/column names as a first row
			  echo implode("t", array_keys($row)) . "n";
			  $heading = true;
			}
			echo implode("t", array_values($row)) . "n";
		  }
		exit;
}

the code shown above, The switch case block will execute based on the parameter value and the method invoked.
Browsers are being forced to download an excel file.

Create HTML and Display Records with Export Button

Define html layout for display data in table and button to fire export-to-csv action. Added below code into the index.php file.

<?php 
include_once("generate_excel.php");
?>

<meta charset="UTF-8" />
<title>Simple Example of Export Excel file using PHP and MySQL</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap-theme.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<title>phpflow.com : Demo of export to excel file</title>

<div id="container">
    <div class="col-sm-6 pull-left">
        <div class="well well-sm col-sm-12">
            <div class="btn-group pull-right">
                <button type="button" class="btn btn-info">Action</button>
                <button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">
                    <span class="caret"></span>
                    <span class="sr-only">Toggle Dropdown</span>
                </button>

                <ul class="dropdown-menu" role="menu" id="export-menu">
                    <li id="export-to-excel"><a href="#">Export to excel</a></li>

                    <li class="divider"></li>

                    <li><a href="#">Other</a></li>
                </ul>
            </div>
        </div>

        <form action="generate_excel.php" method="post" id="export-form">
            <input type="hidden" value="" id="hidden-type" name="ExportType" />
        </form>

        <table id="" class="table table-striped table-bordered">
            <tbody>
                <tr>
                    <th>Name</th>

                    <th>Status</th>

                    <th>Priority</th>

                    <th>Date</th>
                </tr>
            </tbody>
            <tbody>
                <?php foreach($tasks as $row):?>

                <tr>
                    <td><?php echo $row ['Name']?></td>

                    <td><?php echo $row ['Status']?></td>

                    <td><?php echo $row ['Priority']?></td>

                    <td><?php echo $row ['Date']?></td>
                </tr>

                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

We’ve imported the ‘generate_excel.php’ file at the top of the code, which will yield task data for display in the HTML table. We’ve established a dropwodn with a ‘export to excel’ option. All task data will be displayed in an HTML table.

Submit Form Using jQuery

We’ve included a dropdown and need to catch and fire events so that when a user selects an option, the form is submitted. We’ll paste the code below at the bottom of the index.php file.

<script type="text/javascript">
$(document).ready(function() {
jQuery('#Export to excel').bind("click", function() {
var target = $(this).attr('id');
switch(target) {
	case 'export-to-excel' :
	$('#hidden-type').val(target);
	//alert($('#hidden-type').val());
	$('#export-form').submit();
	$('#hidden-type').val('');
	break
}
});
    });
</script>

Result:

export-to-excel with php and mysql
I hope its help you!.

Demo and Download source Code From Below Link

Понравилась статья? Поделить с друзьями:
  • Exporting jqgrid to excel
  • Export excel microsoft sql
  • Exporting images from word
  • Exporting from pdf to word
  • Exporting from oracle to excel