我一直在寻找如何将mysql表导出到csv或excel文件。我已经看到了一些步骤,并且按照它们进行操作。有没有一种方法如何使用codeigniter将mysql表导出到csv或excel文件?
我已经试过这个PHPExcel。但这似乎对我没有用。
function index()
{
$query = $this->db->get('filter_result');
if(!$query)
return false;
// Starting the PHPExcel library
$this->load->library('PHPExcel');
$this->load->library('PHPExcel/IOFactory');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
$objPHPExcel->setActiveSheetIndex(0);
// Field names in the first row
$fields = $query->list_fields();
$col = 0;
foreach ($fields as $field)
{
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
$col++;
}
// Fetching the table data
$row = 2;
foreach($query->result() as $data)
{
$col = 0;
foreach ($fields as $field)
{
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
$col++;
}
$row++;
}
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
// Sending headers to force the user to download the file
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Products_'.date('dMy').'.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
}
这是我使用的代码。
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class excel{
function to_excel($array, $filename) {
header('Content-Disposition: attachment; filename='.$filename.'.xls');
header('Content-type: application/force-download');
header('Content-Transfer-Encoding: binary');
header('Pragma: public');
print "\xEF\xBB\xBF"; // UTF-8 BOM
$h = array();
foreach($array->result_array() as $row){
foreach($row as $key=>$val){
if(!in_array($key, $h)){
$h[] = $key;
}
}
}
echo '<table><tr>';
foreach($h as $key) {
$key = ucwords($key);
echo '<th>'.$key.'</th>';
}
echo '</tr>';
foreach($array->result_array() as $row){
echo '<tr>';
foreach($row as $val)
$this->writeRow($val);
}
echo '</tr>';
echo '</table>';
}
function writeRow($val) {
echo '<td>'.$val.'</td>';
}
}
?>
使用此代码创建一个库,并将其称为:
public function brandExcel() {
$this->load->library('excel');
$result = $this->config_model->getBrandsForExcel();
$this->excel->to_excel($result, 'brands-excel');
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句