gpt4 book ai didi

php - 使用 PHP 导出 excel 时编码字符串错误

转载 作者:行者123 更新时间:2023-12-04 22:00:24 25 4
gpt4 key购买 nike

目前我有一个导出到 excel 的类,它非常适合英语,但是,在其他编码中,例如汉字编码错误

https://github.com/bcit-ci/CodeIgniter/wiki/Export-to-Excel-2013

<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');

/*
* Excel library for Code Igniter applications
* Based on: Derek Allard, Dark Horse Consulting, www.darkhorse.to, April 2006
* Tweaked by: Moving.Paper June 2013
*/

class Export {

function to_excel($array, $filename) {
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename=' . $filename . '.xls');

//Filter all keys, they'll be table headers
$h = array();
foreach ($array->result_array() as $row) {
foreach ($row as $key => $val) {
if (!in_array($key, $h)) {
$h[] = $key;
}
}
}
//echo the entire table headers
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>' . utf8_decode($val) . '</td>';
}

}

尝试添加
header("Content-type: text/html; charset=utf-8");

在函数开始时,但没有运气

非常感谢您的帮助。

最佳答案

代替自定义类,使用 PHPExcel 并完美运行

$this->load->library('PHPExcel');
$this->load->library('PHPExcel/IOFactory');

$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("Trial Report");

// Assign cell values
$objPHPExcel->setActiveSheetIndex(0);

//Filter all keys, they'll be table headers
$h = array();
foreach ($result as $row) {
foreach ($row as $key => $val) {
if (!in_array($key, $h)) {
$h[] = $key;
}
}
}

//Writing the first header row
foreach ($h as $key => $val) {
$val = ucwords($val);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($key, 1, $val); //first row is 1
}

$pos = 0;
foreach ($result as $r_key => $row) {
foreach ($row as $col) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($pos, ($r_key + 2), $col); //skip the first row
$pos++;
}
$pos = 0;
}

$objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');

header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="export.xls"');
$objWriter->save('php://output');

关于php - 使用 PHP 导出 excel 时编码字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36126009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com