自定义PHP Excel导出

时间:2011-02-04 06:43:54

标签: php mysql excel

是否有人知道使用PHP将具有自定义列标题的数据库中的特定字段导出到MSQL中的方法?

这有什么资源?

3 个答案:

答案 0 :(得分:4)

使用PHPExcel库:

// connection with the database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "database";

mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);

// require the PHPExcel file
require 'Classes/PHPExcel.php';

// simple query

$query = "SELECT username,emailAdress,locationCity FROM users ORDER by id DESC";
$headings = array('User Name', 'EMail Address','City');

if ($result = mysql_query($query) or die(mysql_error())) {
    // Create a new PHPExcel object
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getActiveSheet()->setTitle('List of Users');

    $rowNumber = 1;
    $col = 'A';
    foreach($headings as $heading) {
       $objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
       $col++;
    }

    // Loop through the result set
    $rowNumber = 2;
    while ($row = mysql_fetch_row($result)) {
       $col = 'A';
       foreach($row as $cell) {
          $objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
          $col++;
       }
       $rowNumber++;
    }

    // Freeze pane so that the heading line will not scroll
    $objPHPExcel->getActiveSheet()->freezePane('A2');

    // Save as an Excel BIFF (xls) file
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

   header('Content-Type: application/vnd.ms-excel');
   header('Content-Disposition: attachment;filename="userList.xls"');
   header('Cache-Control: max-age=0');

   $objWriter->save('php://output');
   exit();
}
echo 'a problem has occurred... no data retrieved from the database';

使用PHPExcel,您还可以添加格式,或创建包含多个工作表的工作簿等

答案 1 :(得分:1)

Excel会很乐意将CSV文件作为电子表格阅读。 CSV只是一种文本格式,因此创建一些文本并使用适当的内容类型回显它:

$query = "SELECT col1, col2, col3 FROM table";
$result = mysql_query($query);

$csv = '"First Column Title","Second Column Title","Third Column Title"' . "\n";
while ($row = mysql_fetch_assoc($result)) {
    $csv .= '"' . str_replace('"', '""', $row['col1']) . '",';
    $csv .= '"' . str_replace('"', '""', $row['col2']) . '",';
    $csv .= '"' . str_replace('"', '""', $row['col3']) . '"' . "\n";
}

header("Content-type: application/vnd.ms-excel");
echo $csv;

答案 2 :(得分:1)

只需对所需的字段进行选择,然后输出结果,其中的字段以逗号分隔,每行都在其自己的行上。理想情况下,应该用引号括住每个值,并addslashes()来转义数据中的任何引号。

输出结果并保存到名称以.csv结尾的文件中,然后在Excel中打开。