Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHPExcel插入导出Excel?人物_Php_Phpexcel_Export To Excel - Fatal编程技术网

使用PHPExcel插入导出Excel?人物

使用PHPExcel插入导出Excel?人物,php,phpexcel,export-to-excel,Php,Phpexcel,Export To Excel,我正在尝试使用PHPExcel将数据导出为.xls格式。这是我正在使用的代码 require_once "excel/PHPExcel/IOFactory.php"; $query = $this->db->query("SELECT oc_product.product_id,oc_product.model,oc_product.price,oc_product_description.name FROM oc_product LEFT JOIN oc_product_descr

我正在尝试使用PHPExcel将数据导出为
.xls
格式。这是我正在使用的代码

require_once "excel/PHPExcel/IOFactory.php";
$query = $this->db->query("SELECT oc_product.product_id,oc_product.model,oc_product.price,oc_product_description.name FROM oc_product LEFT JOIN oc_product_description ON oc_product_description.product_id=oc_product.product_id");
$product_data = $query->rows;
$objTpl = PHPExcel_IOFactory::load("excel/template.xls");
$objTpl->setActiveSheetIndex(0);  
$i=3;

foreach ($product_data as $prod) 
{
    $objTpl->getActiveSheet()->setCellValue('A'.$i, $prod['product_id']);
    $objTpl->getActiveSheet()->setCellValue('B'.$i, $prod['name']);
    $objTpl->getActiveSheet()->setCellValue('C'.$i, $prod['model']);
    $objTpl->getActiveSheet()->setCellValue('D'.$i, $prod['price']);
    $i++;
}

$objTpl->getActiveSheet()->getStyle('A')->getAlignment()->setWrapText(true);  

$objTpl->getActiveSheet()->getColumnDimension('A')->setWidth(40);  
$filename=mt_rand(1,100000).'.xls'; //just some random filename
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');

$objWriter = PHPExcel_IOFactory::createWriter($objTpl, 'Excel5');  
$objWriter->save('php://output');  
exit;

文件下载得很好,但当我打开文件时,每个字母后面都会显示“?”,比如“D?O?U?B?L?E?F?A?C?E?S?H?E?E?T?S?”。

似乎你的问题与字符编码有关。尝试添加此标题:

header('Content-Type: text/html; charset=UTF-8');
它将强制字符编码;您的输出似乎是16位编码(如unicode或utf16),使用两个字节(char),第一个字节用“?”填充

加:


将强制SQL查询输出中的字符编码

没有人得到相同的响应。请尝试添加
$query=$this->db->query(“设置字符集utf8”)之前选择
;另一个测试可能是用另一个程序打开.xls,比如Libreoffice或openoffice数据库表的字符集是什么?连接到数据库的字符集是什么?您需要确保在单元格中设置的数据是utf-8?
$query = $this->db->query("SET CHARACTER SET utf8");