如何将选定的MySQL数据导出到Excel电子表格

时间:2013-10-29 14:11:50

标签: php mysql excel

我目前正在我的网站的导出端工作,以允许用户查看MySQL数据库中保存的数据。目前,我有一个可行的解决方案,可以将查询中选择的所有数据传递给.CSV文件。

我遇到的问题是我希望能够让用户选择他们自己的数据,然后能够将显示的数据导出到电子表格而不是整个表格。

我首先想到解决这个问题的方法是将执行的查询存储到变量中,然后在使用导出脚本时包含它。

这种方法会被推荐还是我偏离了错误的道路?如果有人可以提供帮助,我将非常感激。

如果这个问题不合适,请你能说明理由。所有反馈对未来的帖子都有用。

1 个答案:

答案 0 :(得分:2)

您需要使用phpexcel库:

我之前写的这个完整的例子

<?php
include("classes/PHPExcel.php");
    set_time_limit(0);

$sql="Select * from datbase";

// Execute the database query
$result = mysql_query($sql) or die(mysql_error());

// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel(); 
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0); 
// Initialise the Excel row number
$rowCount = 1; 
// Iterate through each result from the SQL query in turn
// We fetch each database result row into $row in turn
while($row = mysql_fetch_array($result)){ 
    // Set cell An to the "name" column from the database (assuming you have a column called name)
    //    where n is the Excel row number (ie cell A1 in the first row)

    $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['user_id']); 
    // Set cell Bn to the "age" column from the database (assuming you have a column called age)
    //    where n is the Excel row number (ie cell A1 in the first row)
    $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['email'])); 

    $objPHPExcel->getActiveSheet()->SetCellValue('c'.$rowCount,$row['email']); 

     $objPHPExcel->getActiveSheet()->SetCellValue('d'.$rowCount,$row['email']); 
     $objPHPExcel->getActiveSheet()->SetCellValue('e'.$rowCount,$row['email']); 
      $objPHPExcel->getActiveSheet()->SetCellValue('f'.$rowCount,$row['email']); 
    // Increment the Excel row counter
    $rowCount++;      

} 

$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('all_data.xlsx'); 



?>

有关详情,请参阅广告示例: https://phpexcel.codeplex.com/wikipage?title=Examples

相关问题