Is anyone aware of a method to export specific fields from a database开发者_高级运维 with custom column titles into excel from MSQL using PHP?
Where are there resources on this?
Using the PHPExcel library:
// 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';
Using PHPExcel, you can also add formatting, or create workbooks with multiple worksheets, etc
Excel will happily read a CSV file as a spreadsheet. CSV is just a text format, so create some text and echo it with the appropriate content-type:
$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;
Just do a select on the fields you want, and output the results with fields separated by commas, and each row on its own line. Ideally, should should surround each value with quotes, and addslashes()
to escape any quotes in the data.
Output the result and save to a file with a name ending in .csv
, and open it in Excel.
精彩评论