【问题标题】:Export MySQL data to Excel in PHP在 PHP 中将 MySQL 数据导出到 Excel
【发布时间】:2013-03-19 22:07:23
【问题描述】:

我正在尝试将我的 MySQL 数据导入 Excel 文件,但我遇到了 Excel 单元格的问题。我所有的文本都放在一个单元格中,我希望将每一行的值放在单独的 Excel 单元格中。这是我的代码:

$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 found\n";
   }
}
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);`

【问题讨论】:

  • 与您的问题无关,但您应该真正使用数组来构建文件的行。然后你只需要使用implode 将元素粘合在一起。当您想附加分隔符时,这样可以省去检查当前行缓冲区是否为空的麻烦。
  • @Miklos - 为什么使用内爆? PHP 提供内置函数 fputcsv() 用于写入 CSV/TSV/etc 文件
  • @Mark 感谢提醒,PHP 不是我的主要技能,所以我不知道那个功能。

标签: php mysql excel export


【解决方案1】:

只需尝试以下方法:

PHP部分:

<?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("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        print(trim($schema_insert));
        print "\n";
    }   
?>

我认为这可以帮助您解决问题。

【讨论】:

  • 他显然是在问 excel 而不是 csv 解决方案。同样对于 CSV 文件,您必须使用 application/csv 或 text/csv content-type 而不是 application/vnd.ms-excel (至少这是 CSV 文件的标准。)
  • 还有一件事,即使是 CSV 解决方案也可以,无需使用 PHP 从 mysql 表生成 csv。可以通过sql语句生成SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' FROM test_table;
  • @JohnPeter 我尝试使用代码,但是当我运行页面时,它所做的只是将表格的内容输出到 Web 浏览器中。我将 $filename 变量设置为“testfile”,这可能是我出错的地方吗?另外,这段代码将excel文件输出到哪里?我需要在 $filename 变量中指定目录吗?
  • @JohnPeter :感谢上面的代码,这很好用,但是如果我只想在 Excel 表中导出选定的列(更改了自定义列名)怎么办?我坚持这一点。我不希望我的用户知道存储在用户表中的列名和加密密码的名称。
  • 我得到了解决方案 --- $sep = "\t"; //标签字符回显“名称”。 "\t";回显“电子邮件”。 "\t";打印(“\n”); //打印列名结束 //开始while循环以获取数据 while($row = mysql_fetch_row($result)) { echo $row[1] . "\t";;回声 $row[2] 。 "\t";打印“\n”; } ?>
【解决方案2】:

试试这个代码。它绝对有效。

<?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)) . "\r\n";
        $flag = true;
    }
    echo implode("\t", array_values($row)) . "\r\n";
}
?>

【讨论】:

  • 当我使用此代码时,它可以完美运行,但它也会将整个网页写入文件。知道为什么吗?
  • 使用PHPExcel库更好的解决excel表格导出导入问题
  • 您可以在 while 末尾添加: die();它将停止加载您的页面,内容不应再显示
  • 绝对不是=\
  • 我已提出问题,您能否给我提出问题的声誉并将其标记为有帮助?
【解决方案3】:

如果您只想将查询数据转储到 excel 中,我必须经常这样做,并且使用 html 表是一种非常简单的方法。我使用 mysqli 进行数据库查询,并使用以下代码导出到 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>';

【讨论】:

  • 哇,可以了……但是下载后打开时,excel会显示扩展名和内容不匹配的警告,因此数据可能已损坏。
  • 如果您在导出页面中也有不必要的内容,请在echo '&lt;/table&gt;'; 之后添加exit();
【解决方案4】:

PHPExcel 是您的朋友。非常容易使用,而且效果很好。

https://github.com/PHPOffice/PHPExcel

【讨论】:

【解决方案5】:

这是新版本的php代码

$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("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
    $schema_insert .= "\t";
    print(trim($schema_insert));
    print "\n";
}

【讨论】:

  • @krupeshAnadkat,非常欢迎您,我很高兴为您提供帮助
【解决方案6】:

我认为你应该试试这个 API

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

有了这个

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.**

【讨论】:

    【解决方案7】:

    试试这个代码:

    <?php
        header("Content-type: application/vnd-ms-excel");
    
        header("Content-Disposition: attachment; filename=hasil-export.xls");
    
        include 'view-lap.php';
    ?>
    

    【讨论】:

      【解决方案8】:

      试试这个代码

      数据.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++;
      }
      ?>
      

      excel文件代码

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

      如果是mysqli版本

      $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/

      【讨论】:

        【解决方案9】:

        您可以使用这个简单的代码将数据从 MySQL 导出到 Excel。

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

        完整代码在这里php export to excel

        【讨论】:

          【解决方案10】:

          John Peter 和 Dileep kurahe 的帖子帮助我开发了我认为更简单、更清洁的解决方案,以防万一其他人仍在寻找。 (我没有显示任何数据库代码,因为我实际上使用了 $_SESSION 变量。)

          上述解决方案在加载到 Excel 时总是会导致错误,即扩展名与格式类型不匹配。其中一些解决方案创建了一个电子表格,其中包含跨页面的列中的数据,其中具有列标题并将数据列在行中更为传统。所以这是我的简单解决方案:

          $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.'"' . "\r\n";
          }
          
          1. 更改为 .csv(Excel 会立即更新为 .xls,加载时没有错误。)
          2. 使用逗号作为分隔符。
          3. 双引号键和值以转义数据中的任何逗号。
          4. 我还在 $results 前面添加了列标题,这样电子表格看起来更漂亮。

          【讨论】:

            【解决方案11】:

            请尝试以下代码。 只更新两个值。
            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)) . "\r\n";
                        $flag = true;
                    }
                    echo implode("\t", array_values($row)) . "\r\n";
                }
                ?>
            

            【讨论】:

              【解决方案12】:

              这是基于约翰彼得上面的回答。该代码运行良好,但我需要它用于 WordPress。所以,我做了这样的事情:

              <?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( "/\r\n|\n\r|\n|\r/", " ", $schema_insert );
                      $schema_insert .= "\t";
                      print( trim( $schema_insert ) );
                  }
              }
              

              【讨论】:

                猜你喜欢
                • 2013-09-09
                • 2011-01-12
                • 2011-12-04
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2012-10-25
                • 2016-09-14
                • 1970-01-01
                相关资源
                最近更新 更多