简体   繁体   English

如何使用PHP将MySQL表导出到Excel?

[英]How do I export MySQL table to Excel with PHP?

I am currently developing an App for my school to record Class Cleanliness Results for each class, so I need to convert the results collated in MySQL table into Microsoft Excel using PHP, preferably also able to be opened by a Android OS Phone. 我目前正在为我的学校开发一个应用程序,以记录每个班级的班级清洁度结果,因此我需要使用PHP将MySQL表中整理的结果转换为Microsoft Excel,最好还可以通过Android OS Phone打开。

I used the following PHP code: 我使用了以下PHP代码:

<?PHP

$mysqli_user = "(user)";
$mysqli_password = "(password)";
$mysqli_host = "(host)";
$mysqli_database = "(database)";


  $filename = "grading_results_" . time() . ".xls";

  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: application/vnd.ms-excel");

$link = mysqli_connect($mysqli_host,$mysqli_user,$mysqli_password,$mysqli_database);
$query = 'SELECT * FROM (table_name)';

$result = mysqli_query($link, $query);

while ($row = mysqli_fetch_row($result)){
 print implode("\t", $row) . "\n";
}
mysqli_close($link);
?>

This is how my table looks like in phpMyAdmin: 这是我的表在phpMyAdmin中的样子:

https://www.dropbox.com/s/7pr3gh06zta5d8u/Snip20150618_2.png?dl=0 https://www.dropbox.com/s/7pr3gh06zta5d8u/Snip20150618_2.png?dl=0

This is how the Excel file looks like after I used this code to convert. 这是我使用此代码进行转换后的Excel文件的外观。

https://www.dropbox.com/s/571m9lfj64tklpc/Snip20150618_3.png?dl=0 https://www.dropbox.com/s/571m9lfj64tklpc/Snip20150618_3.png?dl=0

Why is there no columns and rows? 为什么没有列和行? I need the Excel file to be exactly the same formatting and style as the table in phpMyAdmin. 我需要Excel文件的格式和样式与phpMyAdmin中的表完全相同。 Can anyone help edit my code instead of providing me a brand new code? 谁能帮我编辑代码,而不是为我提供全新的代码?

Thanks in advance for your answers! 预先感谢您的回答!

Manual 手册

  1. Run tour localhost and log in to phpMyAdmin 运行游览localhost并登录到phpMyAdmin
  2. Click on your database then click on the table which you want to get Excel. 单击数据库,然后单击要获取Excel的表。
  3. 图片

then 然后

  1. 在此处输入图片说明
  2. then press GO button 然后按GO按钮

With Code 带代码

define ("DB_HOST", "localhost");
define ("DB_USER", "root");
define ("DB_PASS","");
define ("DB_NAME","DATABASE_NAME");

$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");

then 然后

$setCounter = 0;

$setExcelName = "download_excal_file";

$setSql = "YOUR SQL QUERY GOES HERE";

$setRec = mysql_query($setSql);

$setCounter = mysql_num_fields($setRec);

for ($i = 0; $i < $setCounter; $i++) {
    $setMainHeader .= mysql_field_name($setRec, $i)."\t";
}

while($rec = mysql_fetch_row($setRec))  {
  $rowLine = '';
  foreach($rec as $value)       {
    if(!isset($value) || $value == "")  {
      $value = "\t";
    }   else  {
//It escape all the special charactor, quotes from the data.
      $value = strip_tags(str_replace('"', '""', $value));
      $value = '"' . $value . '"' . "\t";
    }
    $rowLine .= $value;
  }
  $setData .= trim($rowLine)."\n";
}
  $setData = str_replace("\r", "", $setData);

if ($setData == "") {
  $setData = "no matching records found";
}

$setCounter = mysql_num_fields($setRec);



//This Header is used to make data download instead of display the data
 header("Content-type: application/octet-stream");

header("Content-Disposition: attachment; filename=".$setExcelName."_Report.xls");
header("Pragma: no-cache");
header("Expires: 0");

//It will print all the Table row as Excel file row with selected column name as header.
echo ucwords($setMainHeader)."\n".$setData."\n";

More About Code 有关代码的更多信息

SELECT id, name, email INTO OUTFILE '/tmp/ram.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY ‘\\’
LINES TERMINATED BY '\n'
FROM users WHERE id=1

Here /tmp/ is address where u want to store the csv /tmp/是您要存储csv的地址

  <?php
    header( "Content-Type: application/vnd.ms-excel" );
    header( "Content-disposition: attachment; filename=spreadsheet.xls" );

    // print your data here. note the following:
    // - cells/columns are separated by tabs ("\t")
    // - rows are separated by newlines ("\n")

    // for example:
    echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
    echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
?>

// You can fetch the data from the database and display in the table. //您可以从数据库中获取数据并显示在表中。 Then put the table in echo to get Excel file. 然后将表放入echo中以获取Excel文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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