简体   繁体   中英

Exporting data from MySQL to Excel with PHP

I want to export the data in the gotten from det SQL to a spreadsheet, using PHP.

$sql_export = "SELECT id_employee, firstname, email FROM employees WHERE id_employee = 1";

$export_result = $db->query($sql_export);

This code working for me.Try this code and make some changes as you needed.

**excl_1.php**

    <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

**export.php**





     <?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;
         }
        }
        ?>

Test Result在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM