Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial PHPExcel 向单元格插入图片就换行的问题

PHPExcel 向单元格插入图片就换行的问题

Jun 23, 2016 pm 01:59 PM

要用phpexcel从数据库中将表导出为excel格式,表中存放有图片路径现在我的代码如下:

<?php    require_once 'PHPExcel.php';    require_once 'PHPExcel/Writer/Excel5.php'; include_once 'DB_connmssql.php';$sql="select.....";$query = mssql_query($sql);$items = array();// 创建一个处理对象实例    $objExcel = new PHPExcel();       // 创建文件格式写入对象实例, uncomment    $objWriter = new PHPExcel_Writer_Excel5($objExcel);    //设置文档基本属性    $objProps = $objExcel->getProperties();    $objProps->setCreator("tt");    $objProps->setLastModifiedBy("tt");    $objProps->setTitle("tt");    $objProps->setSubject("tt ");    $objProps->setDescription("tt ");    $objProps->setKeywords("tt ");    $objProps->setCategory("变动报表");       //*************************************    //设置当前的sheet索引,用于后续的内容操作。    //一般只有在使用多个sheet的时候才需要显示调用。    //缺省情况下,PHPExcel会自动创建第一个sheet被设置SheetIndex=0    $objExcel->setActiveSheetIndex(0);    $objActSheet = $objExcel->getActiveSheet();       //设置当前活动sheet的名称    $objActSheet->setTitle('tttt');       //*************************************    //    //设置宽度,这个值和EXCEL里的不同,不知道是什么单位,略小于EXCEL中的宽度$objActSheet->getColumnDimension('A')->setWidth(20); $objActSheet->getColumnDimension('B')->setWidth(15); $objActSheet->getRowDimension(1)->setRowHeight(30); $objActSheet->getRowDimension(2)->setRowHeight(27); $objActSheet->getRowDimension(3)->setRowHeight(16);  //设置单元格的值  $objActSheet->setCellValue('A1', 'Titile'); //合并单元格$objActSheet->mergeCells('A1:N1'); //设置样式$objStyleA1 = $objActSheet->getStyle('A1');    $objStyleA1->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);$objFontA1 = $objStyleA1->getFont();    $objFontA1->setName('宋体');    $objFontA1->setSize(18);  $objFontA1->setBold(true);    //设置居中对齐$objActSheet->getStyle('A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);$objActSheet->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);$objActSheet->setCellValue('A2', 'Shoes Picture'); $objActSheet->setCellValue('B2', 'Product code'); //设置边框$objActSheet->getStyle('A2')->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$objActSheet->getStyle('A2')->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$objActSheet->getStyle('A2')->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$objActSheet->getStyle('A2')->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$objActSheet->getStyle('B2')->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$objActSheet->getStyle('B2')->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$objActSheet->getStyle('B2')->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$objActSheet->getStyle('B2')->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$i=1;$query = mssql_query($sql);$query1 = mssql_query($sql);$items=array();$sales_sum=$sales_sum+$row1["total_sales"];while($row=mssql_fetch_array($query)){	$row["Photo"]="../picture/".$row["Photo"];	$n=$i+2;	$objActSheet->getStyle('B'.$n)->getNumberFormat()->setFormatCode('@');	$objActSheet->getStyle('E'.$n)->getNumberFormat()->setFormatCode('@');	$objActSheet->getRowDimension($n)->setRowHeight(16);	$objActSheet->getStyle('A'.$n)->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$objActSheet->getStyle('A'.$n)->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$objActSheet->getStyle('A'.$n)->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$objActSheet->getStyle('A'.$n)->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$objActSheet->getStyle('B'.$n)->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$objActSheet->getStyle('B'.$n)->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$objActSheet->getStyle('B'.$n)->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$objActSheet->getStyle('B'.$n)->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );	$objActSheet->setCellValue('A'.$n, $row["Photo"]);	$objActSheet->setCellValue('B'.$n, $row["Article_No"]);		$i++;} $outputFileName = "tables addminus1.xls";    header("Content-Type: application/force-download");header("Content-Type: application/octet-stream");header("Content-Type: application/download");header('Content-Disposition:inline;filename="'.$outputFileName.'"');header("Content-Transfer-Encoding: binary");header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");header("Cache-Control: must-revalidate, post-check=0, pre-check=0");header("Pragma: no-cache");$objWriter->save('php://output');  ?>    
Copy after login

导出的excel如下

请教下 要把图片的路径换成真实的图片输出代码该怎么修改? 还有怎么让excel的标题分成两行显示并加粗,代码该如何修改?


回复讨论(解决方案)

图片如下

标题换行只需在需要换行的地方加上换行符
比如 "Product \ncode"

其他的明天说

标题换行只需在需要换行的地方加上换行符
比如 "Product \ncode"

其他的明天说

$objActSheet->setCellValue('A2', 'Shoes Picture'); $objActSheet->setCellValue('B2', 'Product code'); $objActSheet->setCellValue('C2', 'Original Retail  Price (VAT)'); $objActSheet->setCellValue('D2', '  Total \nOrdered Qty'); $objActSheet->setCellValue('E2', '  Total 		Sales Qty'); $objActSheet->setCellValue('F2', 'Sellthru'); $objActSheet->setCellValue('G2', 'Total Sales'); $objActSheet->setCellValue('H2', 'Cumulated Qty'); $objActSheet->setCellValue('I2', 'Cumulated  /nQty %'); 
Copy after login

/n \n都试过了...都不行。

加粗 范例
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);

添加图片 范例
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Logo');
$objDrawing->setDescription('Logo');
$objDrawing->setPath('./images/officelogo.jpg');
$objDrawing->setHeight(36);
$objDrawing->setCoordinates('B15');
$objDrawing->setOffsetX(110);
$objDrawing->setRotation(25);
$objDrawing->getShadow()->setVisible(true);
$objDrawing->getShadow()->setDirection(45);
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());

加粗 范例
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);

添加图片 范例
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Logo');
$objDrawing->setDescription('Logo');
$objDrawing->setPath('./images/officelogo.jpg');
$objDrawing->setHeight(36);
$objDrawing->setCoordinates('B15');
$objDrawing->setOffsetX(110);
$objDrawing->setRotation(25);
$objDrawing->getShadow()->setVisible(true);
$objDrawing->getShadow()->setDirection(45);
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
插入图片的代码该加到哪儿呢?我这样加不对

$objDrawing = new PHPExcel_Worksheet_Drawing();while($row=mssql_fetch_array($query)){	if(''!==$row["Photo"]){	$row["Photo"]="../picture/".$row["Photo"];	$objDrawing->setName('Logo');	$objDrawing->setDescription('Logo');	$objDrawing->setPath($row["Photo"]);	$objDrawing->setHeight(36);	$objDrawing->setCoordinates('B15');	$objDrawing->setOffsetX(110);	$objDrawing->setRotation(25);	$objDrawing->getShadow()->setVisible(true);	$objDrawing->getShadow()->setDirection(45);	$objDrawing->setWorksheet($objExcel->getActiveSheet());	}
Copy after login

$objDrawing = new PHPExcel_Worksheet_Drawing();
要放在循环内,即每个图片需要一个 PHPExcel_Worksheet_Drawing 实例

setHeight 图片高
setCoordinates 所在单元格
setOffsetX 左上角相对单元格的x偏移
setRotation 旋转角
更多的方法请见文档

$objDrawing = new PHPExcel_Worksheet_Drawing();
要放在循环内,即每个图片需要一个 PHPExcel_Worksheet_Drawing 实例

setHeight 图片高
setCoordinates 所在单元格
setOffsetX 左上角相对单元格的x偏移
setRotation 旋转角
更多的方法请见文档
导出来了,只是位置不对,要把图片设置到单元格里代码该怎么修改?

我 setCoordinates('B15') (15行B列)
你也在 setCoordinates('B15') 吗?

我 setCoordinates('B15') (15行B列)
你也在 setCoordinates('B15') 吗?
果然这样,但又有个问题,我把图片设置到了图片名称出现的位置。

while($row=mssql_fetch_array($query)){	$objDrawing = new PHPExcel_Worksheet_Drawing();	if(''!==$row["Photo"]){	$row["Photo"]="picture/".$row["Photo"];	$objDrawing->setName('Logo');	$objDrawing->setDescription('Logo');	$objDrawing->setPath($row["Photo"]);	$objDrawing->setHeight(36);	$objDrawing->setCoordinates('A'.$aa);//图片名称所在的单元格	$objDrawing->setOffsetX(80);	$objDrawing->setRotation(25);	$objDrawing->getShadow()->setVisible(true);	$objDrawing->getShadow()->setDirection(45);	$objDrawing->setWorksheet($objExcel->getActiveSheet());	$aa++;	}
Copy after login

出来效果是这样的

图片只是出现在单元格的位置,并不是单元格的值
要达到下面的效果该怎么设置单元格?

不是说了吗?
$objDrawing->setOffsetX(80); //表示图片左边距是 80
$objDrawing->setRotation(25); //表示旋转 25 度
显然都不是你需要的
你只需设置单元格居中排列

批量设置,我一般用 PHPExcel_Style 来写,如

	$style_obj = new PHPExcel_Style(); 	$style_array = array( 		'borders' => array( 			'top' => array('style' => PHPExcel_Style_Border::BORDER_THIN),			'left' => array('style' => PHPExcel_Style_Border::BORDER_THIN),			'bottom' => array('style' => PHPExcel_Style_Border::BORDER_THIN),			//'right' => array('style' => PHPExcel_Style_Border::BORDER_THIN) 			),		'alignment' => array(			'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,			'vertical'	=> PHPExcel_Style_Alignment::VERTICAL_CENTER,			'wrap'	=> true			)		);	$style_obj->applyFromArray($style_array); 	$sheet->setSharedStyle($style_obj, "B$y:$x$y");
Copy after login
Copy after login

当然一个个的设置也是没有问题的

不是说了吗?
$objDrawing->setOffsetX(80); //表示图片左边距是 80
$objDrawing->setRotation(25); //表示旋转 25 度
显然都不是你需要的
你只需设置单元格居中排列

批量设置,我一般用 PHPExcel_Style 来写,如

	$style_obj = new PHPExcel_Style(); 	$style_array = array( 		'borders' => array( 			'top' => array('style' => PHPExcel_Style_Border::BORDER_THIN),			'left' => array('style' => PHPExcel_Style_Border::BORDER_THIN),			'bottom' => array('style' => PHPExcel_Style_Border::BORDER_THIN),			//'right' => array('style' => PHPExcel_Style_Border::BORDER_THIN) 			),		'alignment' => array(			'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,			'vertical'	=> PHPExcel_Style_Alignment::VERTICAL_CENTER,			'wrap'	=> true			)		);	$style_obj->applyFromArray($style_array); 	$sheet->setSharedStyle($style_obj, "B$y:$x$y");
Copy after login
Copy after login

当然一个个的设置也是没有问题的
格式搞定了 现在就剩两个问题了:
1、导出图片到cell里面。
2、页面上有导出excel按钮,怎么通过点击按钮,将页面的参数传到后台(前台页面不跳转)以导出对应的excel。
大师把这个分数一起拿走吧 小弟分数不多... http://bbs.csdn.net/topics/390730241

1、导出图片上面已经说了,你也做到了。只是要注意调整格式
2、导出excel按钮可以是表单的提交按钮,设置表单的 target 指向一个隐藏的 iframe 就不会跳转了

<form method=post action=excel.php target=down><input type=submit value='导出excel'></form><iframe name=down style='display:none'></iframe>
Copy after login
Copy after login

1、导出图片上面已经说了,你也做到了。只是要注意调整格式
2、导出excel按钮可以是表单的提交按钮,设置表单的 target 指向一个隐藏的 iframe 就不会跳转了

<form method=post action=excel.php target=down><input type=submit value='导出excel'></form><iframe name=down style='display:none'></iframe>
Copy after login
Copy after login

大师 再请教个问题,向excel中写入图片时,当图片不存在,phpexcel会抛出异常不能形成excel文件,于是我捕获异常(被注释掉的代码)
if(''!==$row["Photo"]){	//	$row["Photo"]="picture/".$row["Photo"];	//try{		$objDrawing->setName('Logo');		$objDrawing->setDescription('Logo');		$objDrawing->setPath($row["Photo"]);		$objDrawing->setHeight(36);		$objDrawing->setCoordinates('A'.$n);//图片名称所在的单元格		$objDrawing->setOffsetX(15);		$objDrawing->setRotation(25);		$objDrawing->getShadow()->setVisible(true);		$objDrawing->getShadow()->setDirection(45);		$objDrawing->setWorksheet($objExcel->getActiveSheet());// 	}catch (Exception $e){// 		$objDrawing->setName('Logo1');// 		$objDrawing->setDescription('Logo1');// 		$objDrawing->setPath("notf.jpg");// 		$objDrawing->setHeight(36);// 		$objDrawing->setCoordinates('A'.$n);//图片名称所在的单元格// 		$objDrawing->setOffsetX(15);// 		$objDrawing->setRotation(25);// 		$objDrawing->getShadow()->setVisible(true);// 		$objDrawing->getShadow()->setDirection(45);// 		$objDrawing->setWorksheet($objExcel->getActiveSheet());// 	}	}
Copy after login

这样就算图片不存在也能导出excel,但导出的excel就是打不开,请问如何解决?

if(file_exists("picture/".$row["Photo"])) {   .....  $objDrawing->setWorksheet($objExcel->getActiveSheet());}
Copy after login
Copy after login

if(file_exists("picture/".$row["Photo"])) {   .....  $objDrawing->setWorksheet($objExcel->getActiveSheet());}
Copy after login
Copy after login

请问大师 输出pdf文档该怎么输出呢?
我这样输出文件很小很小,而且打不开
/输出内容    // if($outtype=="pdf"){// header('Content-Type: application/pdf');// header('Content-Disposition: attachment;filename="Global Network.pdf"');// header('Cache-Control: max-age=0');// $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'PDF');// $objWriter->save('php://output');// exit;//}ELSE{$outputFileName = "Global Network.xls";    //到文件    //$objWriter->save($outputFileName);    //到浏览器header("Content-Type: application/force-download");header("Content-Type: application/octet-stream");header("Content-Type: application/download");header('Content-Disposition:inline;filename="'.$outputFileName.'"');header("Content-Transfer-Encoding: binary");header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");// header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");header("Cache-Control: must-revalidate, post-check=0, pre-check=0");header("Pragma: no-cache");$objWriter->save('php://output');  //exit;//}
Copy after login

我没做过,刚才试了一下
不但样式难看,而且不能显示中文

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1667
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles