Ale*_*ria 5 php image alignment phpexcel
我正在尝试使用 PHPExcel 对齐图像,但我不能,因为图像覆盖在工作表上方。
// Create new picture object
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setPath('my_img.jpg');
// Insert picture
$objDrawing->setCoordinates('A1');
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
// Style cell
$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
Run Code Online (Sandbox Code Playgroud)
A1 的文本对齐更改为右对齐,但图像仍然左对齐。
面临同样的挑战:如何将图片与单元格右对齐。我正在使用 PHP 电子表格,它继承了 PHP Excel。这有效:
use PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
$ws = $spreadsheet->getActiveSheet();
$logoPath = __DIR__ . '/reporting/templates/SmallLogo.jpg';
$drawing = new Drawing();
$drawing->setPath($logoPath);
$drawing->setCoordinates('K2');
$drawing->setHeight(45); //pixels
$colWidth = $ws->getColumnDimension('K')->getWidth();
if ($colWidth == -1) { //not defined which means we have the standard width
$colWidthPixels = 64; //pixels, this is the standard width of an Excel cell in pixels = 9.140625 char units outer size
} else { //innner width is 8.43 char units
$colWidthPixels = $colWidth * 7.0017094; //colwidht in Char Units * Pixels per CharUnit
}
$offsetX = $colWidthPixels - $drawing->getWidth(); //pixels
$drawing->setOffsetX($offsetX); //pixels
$drawing->setWorksheet($ws);
Run Code Online (Sandbox Code Playgroud)
它与 PHPExcel 的工作方式应该相同。技巧是将列宽转换为 Excel 像素,并使用 offsetX 获取距左侧水平列边框的右侧偏移量。如果图片比列宽,则偏移量将为负。
这是一个想法:
您需要确定最大宽度/高度(通过实验)。保存值。
// Logo
$maxWidth = 700;
$maxHeight = 40;
Run Code Online (Sandbox Code Playgroud)
这是其余的代码:
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
$objDrawing->setName("Logo");
$objDrawing->setDescription("Company Logo");
$objDrawing->setPath('logo.png');
$objDrawing->setCoordinates('A1');
$objDrawing->setHeight($maxHeight);
// This is the "magic" formula
$offsetX =$maxWidth - $objDrawing->getWidth();
$objDrawing->setOffsetX($offsetX);
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
15145 次 |
| 最近记录: |