2016-08-11 92 views
0

所以我無法從MySQL的數據導出到ExcelPHP在正確的格式不出口的MySQL數據庫

$output = ''; 
if(isset($_POST["export_excel"])) 
{ 
     $sql = "SELECT * FROM Logs ORDER BY item"; 
     $result = mysqli_query($connect, $sql); 
     if(mysqli_num_rows($result) > 0) 
     { 
      $output .= ' 
       <table class="table bordered="1"> 
        <tr> 
          <th>Sort</th> 
          <th>Unit Size</th> 
          <th>Quantity</th> 
          <th>Price per Unit</th> 
          <th>Time</th> 
        </tr> 
      '; 
      while($row = mysqli_fetch_array($result)) 
      { 
       $output .= ' 
        <tr> 
          <td>'.$row["Sort"].'</td> 
          <td>'.$row["Unit Size"].'</td> 
          <td>'.$row["Quantity"].'</td> 
          <td>'.$row["Price per Unit"].'</td> 
          <td>'.$row["Time"].'</td> 
        </tr> 
       '; 
      } 
      $output .= '</table>'; 
      header("Content-Type: application/xls"); 
      header("Content-Disposition: attachment; filename=download.xls"); 
      echo $output; 
     } 
} 

所以,當我打我的index.php頁面上的出口按鈕,它以這種格式輸出數據:Google Sheets Link to the excel file

<table class="table bordered="1"> 
<tr>  
<th>Sort</th> 
<th>Unit Size</th> 
<th>Quantity</th> 
<th>Price per Unit</th> 
<th>Time</th> 
</tr> 

<tr>  
<td></td> 
<td>45</td> 
<td>0</td> 
<td>0</td> 
<td>2016-08-11 16:53:12</td>  
</tr> 

<tr>  
<td></td> 
<td>6</td> 
<td>0</td> 
<td>0</td> 
<td>2016-08-11 16:53:12</td>  
</tr> 
</table>  

所以輸出正確的數據,但只是格式化是關閉的,這裏是什麼樣子的index.php頁面上: What the excel file should look like 做,如果任何人都可以告訴我,我做錯了那太棒了! 預先感謝您!

+0

MS Excel可以打開html文件並將表格顯示爲excel電子表格,但這不是一個有效的xls文件,因此google-spreadsheets無法正確讀取它。 – Dekel

+0

你會更好地寫入數據作爲CSV格式的數據而不是HTML – RamRaider

回答

0

也許有點作爲CSV而不是proper xls輸出作弊,但它應該或多或少的工作。

<?php 

    if(isset($_POST["export_excel"])) { 

     ob_clean(); 

     $sql = 'select * from logs order by item'; 
     $result = mysqli_query($connect, $sql); 
     if(mysqli_num_rows($result) > 0){ 


      $delimiter=','; 
      $enclosure='"'; 

      /* rather than create an actual file, use an output buffer and write to that */ 
      $output=fopen('php://output','w+'); 

      /* add column headers */ 
      $headers=array('Unit Size', 'Quantity', 'Price_per_Unit', 'Time'); 

      /* write the headers to the output stream */ 
      fputcsv($output,$headers, $delimiter, $enclosure); 

      /* loop through recordset and add that to the stream */ 
      while($row = mysqli_fetch_array($result)) { 
       fputcsv($output, $row, $delimiter, $enclosure); 
      } 

      fclose($output); 

      /* set the headers accordingly */ 
      header('Content-Type: application/csv'); 
      header('Content-Disposition: attachment; filename=download.csv'); 

      /* send the new content */ 
      ob_flush(); 

     } 
    } 

?> 
+0

是的,這是做的伎倆,謝謝大家的幫助! – Ninjaboi

0

如果我正確地理解你,你想將數據導出到excel。在這種情況下,只需更改標題將不起作用,因爲excel不是關於表標記,您需要的是將內容寫入excel格式文件並使用戶下載相同的庫。看看phpExcel

您還可以在示例here中看到如何使用相同的方法在Excel中正確插入數據。