How to export Excel file and set column width in native PHP?
Mar 31, 2025 pm 11:18 PMHow to accurately control column width is a common problem when native PHP exports Excel files. This article will explain in detail how to use PHP code to export Excel files and set column widths to solve the problem of inconsistent column widths of exported data.
For example, you need to export three columns of data "Alipay Account", "Name", and "Payment Amount" and set their column widths respectively. The column width setting cannot be achieved by directly using the fputcsv
function. We need to use the PHPExcel library.
Improved method: Use PHPExcel library
The following code demonstrates how to set column width using the PHPExcel library:
// Import the PHPExcel class library (please make sure that PHPExcel is installed correctly) require_once 'Classes/PHPExcel.php'; // Replace with the actual path of the PHPExcel library// Create a PHPExcel object $objPHPExcel = new PHPExcel(); // Set column width (unit: character width) $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20); // Alipay account $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15); // Name $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10); // Payment amount// Set the header $title = array('Alipay account','name','Paid amount'); $objPHPExcel->getActiveSheet()->fromArray($title, null, 'A1'); // Fill in data $row = 2; foreach($list as $val){ $data = array( $val['alipay_acount'], $val['alipay_real_name'], $val['total_check_che'] ); $objPHPExcel->getActiveSheet()->fromArray($data, null, 'A'.$row); $row ; } // Save as Excel 2007 format (.xlsx) $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="Article Information Statistics'.date('ymdHis').'.xlsx"'); header('Cache-Control: max-age=0'); $objWriter->save('php://output');
This code first introduces the PHPExcel library, then creates the PHPExcel object, and sets the widths of the 'A', 'B', 'C' columns respectively using getColumnDimension()
method. After that, the data is filled with fromArray()
method, and finally the data is saved in xlsx format using Excel2007
writer and output.
Set column width in batches (optional)
If you need to set the column width in batches, you can use a loop:
$cols = range('A', 'Z'); // Set the width of column A to Z foreach ($cols as $col) { $objPHPExcel->getActiveSheet()->getColumnDimension($col)->setWidth(15); // Set all column widths to 15 }
This loop can modify the range and width of the column as needed.
Summarize
By using the PHPExcel library, we can easily control the column width of the export Excel file, thereby achieving better data display results. Please make sure that the PHPExcel library is installed and configured correctly and adjust the require_once
statement in the code according to the actual path. This method is more flexible than using fputcsv
, which can better meet various Excel export needs.
The above is the detailed content of How to export Excel file and set column width in native PHP?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

H5 development tools recommendations: VSCode, WebStorm, Atom, Brackets, Sublime Text; Mini Program Development Tools: WeChat Developer Tools, Alipay Mini Program Developer Tools, Baidu Smart Mini Program IDE, Toutiao Mini Program Developer Tools, Taro.

The choice of H5 and applet depends on the requirements. For applications with cross-platform, rapid development and high scalability, choose H5; for applications with native experience, rich functions and platform dependencies, choose applets.

There are differences in the promotion methods of H5 and mini programs: platform dependence: H5 depends on the browser, and mini programs rely on specific platforms (such as WeChat). User experience: The H5 experience is poor, and the mini program provides a smooth experience similar to native applications. Communication method: H5 is spread through links, and mini programs are shared or searched through the platform. H5 promotion methods: social sharing, email marketing, QR code, SEO, paid advertising. Mini program promotion methods: platform promotion, social sharing, offline promotion, ASO, cooperation with other platforms.

The secrets to mastering Office software include: understanding different versions and platforms, correctly installing and configuring, proficient in using the software interface, in-depth understanding of feature operations, application collaboration and sharing functions, utilizing templates and styles, mastering advanced skills, and solving common problems. In addition, you need to choose a version that suits your needs, make good use of templates and styles, develop backup habits, and learn shortcut keys and advanced techniques to improve efficiency.

The best cryptocurrency trading and analysis platforms include: 1. OKX: the world's number one in trading volume, supports multiple transactions, provides AI market analysis and on-chain data monitoring. 2. Binance: The world's largest exchange, providing in-depth market conditions and new currency first-time offerings. 3. Sesame Open Door: Known for spot trading and OTC channels, it provides automated trading strategies. 4. CoinMarketCap: an authoritative market data platform, covering 20,000 currencies. 5. CoinGecko: Known for community sentiment analysis, it provides DeFi and NFT trend monitoring. 6. Non-small account: a domestic market platform, providing analysis of linkage between A-shares and currency markets. 7. On-chain Finance: Focus on blockchain news and update in-depth reports every day. 8. Golden Finance: 24 small

Method: Use Microsoft Excel to open an XML file and select the XML Data file type. Use third-party tools such as XML to XLSX Converter, Altova MapForce, or Oxygen XML Editor.

How to stop Microsoft Edge Automatically Update Microsoft Edge is the default browser that comes with Windows 11. Earlier, the Edge browser received updates as the Windows operating system was updated. However, the Edge browser based on Chromium has changed that. The browser will now automatically update in the background without your knowledge. In this article, we will explain how to stop automatic Microsoft Edge updates in Windows 11 and macOS. Related: How to disable automatic updates in Google Chrome? Check for automatic edge updates Chromium-based Edge vs. Goo based on Chromium backend code
