Home Backend Development PHP Tutorial How to export Excel file and set column width in native PHP?

How to export Excel file and set column width in native PHP?

Mar 31, 2025 pm 11:18 PM
Alipay office

How to export Excel file and set column width in native PHP?

How 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');
Copy after login

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
}
Copy after login

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!

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 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)

How to convert deepseek pdf How to convert deepseek pdf Feb 19, 2025 pm 05:24 PM

DeepSeek cannot convert files directly to PDF. Depending on the file type, you can use different methods: Common documents (Word, Excel, PowerPoint): Use Microsoft Office, LibreOffice and other software to export as PDF. Image: Save as PDF using image viewer or image processing software. Web pages: Use the browser's "Print into PDF" function or the dedicated web page to PDF tool. Uncommon formats: Find the right converter and convert it to PDF. It is crucial to choose the right tools and develop a plan based on the actual situation.

How to solve the problem of 'Undefined array key 'sign'' error when calling Alipay EasySDK using PHP? How to solve the problem of 'Undefined array key 'sign'' error when calling Alipay EasySDK using PHP? Mar 31, 2025 pm 11:51 PM

Problem Description When calling Alipay EasySDK using PHP, after filling in the parameters according to the official code, an error message was reported during operation: "Undefined...

Download ppt finished product. Easy to use ppt finished product website for free Download ppt finished product. Easy to use ppt finished product website for free Mar 11, 2025 am 10:24 AM

Still worried about finding high-quality PPT templates? This article recommends 15 excellent websites that provide PPT template downloads, including Microsoft Office Template Library, Canva, Slidesgo, Envato Elements, etc. These websites provide templates with diverse styles, strong compatibility, exquisite design and suitable for different scenarios (business, education, creative display, etc.), covering free and paid resources. Some websites also provide online editing and collaboration functions to meet your various PPT production needs and help you easily create amazing presentations. Click to view the detailed introduction and find your favorite template!

List of handling fees for okx trading platform List of handling fees for okx trading platform Feb 15, 2025 pm 03:09 PM

The OKX trading platform offers a variety of rates, including transaction fees, withdrawal fees and financing fees. For spot transactions, transaction fees vary according to transaction volume and VIP level, and adopt the "market maker model", that is, the market charges a lower handling fee for each transaction. In addition, OKX also offers a variety of futures contracts, including currency standard contracts, USDT contracts and delivery contracts, and the fee structure of each contract is also different.

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

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.

Ouyi Exchange app domestic download tutorial Ouyi Exchange app domestic download tutorial Mar 21, 2025 pm 05:42 PM

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

Sesame Open Door Login Registration Entrance gate.io Exchange Registration Official Website Entrance Sesame Open Door Login Registration Entrance gate.io Exchange Registration Official Website Entrance Mar 04, 2025 pm 04:51 PM

Gate.io (Sesame Open Door) is the world's leading cryptocurrency trading platform. This article provides a complete tutorial on spot trading of Gate.io. The tutorial covers steps such as account registration and login, KYC certification, fiat currency and digital currency recharge, trading pair selection, limit/market transaction orders, and orders and transaction records viewing, helping you quickly get started on the Gate.io platform for cryptocurrency trading. Whether a beginner or a veteran, you can benefit from this tutorial and easily master the Gate.io trading skills.

See all articles