gpt4 book ai didi

php - 使用 PHPExcel 导出时,MySQL 数据仅在一列中导出到 Excel

转载 作者:行者123 更新时间:2023-11-30 21:43:32 25 4
gpt4 key购买 nike

我正在尝试使用 PHPExcel 将我的数据从 MySQL 分离到一个 excel 文件。我希望数据按行分隔。
例如,
详细信息 1 响应 1 状态 1
细节 2 响应 2 状态 2
详细信息3 响应3 状态3

数据的分隔符是||,每行的分隔符是::

这是数据: enter image description here

这是我的代码:

<?php 


try {

$sql = "SELECT ID,DESCRIPTION FROM SAMPLE";


} catch (Exception $ex) {
echo 'Message: ' .$ex->getMessage();
}

$connect = @mysql_connect($dbhost, $dbuser, $dbpass)

or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = @mysql_select_db($dbname, $connect)
or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
//execute query
$result = @mysql_query($sql,$connect)
or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());

error_reporting(E_ALL);


require_once 'Classes/PHPExcel.php';

// Execute the database query
// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);

$rowCount = 2;


$objPHPExcel->getActiveSheet()->setCellValue('A1', 'ID');
$objPHPExcel->getActiveSheet()->setCellValue('B1', 'DESCRIPTION');

while($row = mysql_fetch_array($result)){

$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['ID']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['DESCRIPTION']);

}


header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="SampleExcel.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

?>

更新

我现在在如何解决我的问题上取得了进展 :) 我已经使用 MySQL 查询创建了一个分隔符,我的数据现在被放置在行中。

结果 enter image description here

现在,我现在想要的是用分隔符“||”将它们分开。你能帮我吗?

这是我的查询:

SELECT SUBSTRING_INDEX(SELECT sample.id, SUBSTRING_INDEX(SUBSTRING_INDEX(sample.DESCRIPTION, '::', numbers.n), '::', -1) as name FROM numbers INNER JOIN sample ON CHAR_LENGTH(sample.DESCRIPTION) -CHAR_LENGTH(REPLACE(sample.DESCRIPTION, '::', ''))>=numbers.n-1,'||'-2) as string

最佳答案

我看不到您在哪里递增变量 $rowCount

您应该在 while 循环的末尾编写 ++$rowCount;

while($row = mysql_fetch_array($result)) {  
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['ID']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['DESCRIPTION']);

++$rowCount;
}

关于php - 使用 PHPExcel 导出时,MySQL 数据仅在一列中导出到 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50540389/

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