Hongmu Notes
Home Language Notes Export database data to Excel using PHP
Language Notes PHP PHP and mysql

Export database data to Excel using PHP

Export database data to Excel using PHP

To export data from a database to an Excel file, you can use thePHPExcel library in PHP. Here is a simple example code that usesPHPExcel to retrieve data from a database and export it to an Excel file:

// 导入PHPExcel库
require_once 'PHPExcel.php';

// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接是否成功
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// 查询数据库中的数据
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// 创建一个新的PHPExcel对象
$objPHPExcel = new PHPExcel();

// 设置当前工作表
$objPHPExcel->setActiveSheetIndex(0);

// 将数据添加到工作表中
$row = 1;
while($row_data = $result->fetch_assoc()) {
    $col = 0;
    foreach($row_data as $value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
        $col++;
    }
    $row++;
}

// 设置文件名和格式
$file_name = "database_info.xls";

// 用于告诉浏览器要下载的文件的类型和格式
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$file_name.'"');
header('Cache-Control: max-age=0');

// 将Excel文件输出到浏览器
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

// 关闭数据库连接
$conn->close();

In the above example code, first, use mysqli to connect to the database. Then, query the data from the database and add it to aPHPExcel object. Next, set the file name and format, and use the header() function to specify the file type and format to be downloaded by the browser. Finally, output the Excel file to the browser and close the database connection.

Please note that this code is only suitable for exporting smaller datasets. If you need to export large amounts of data, consider using batch export or other export options.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232
PHP special character escaping and restoration

PHP special character escaping and restoration Language Notes PHP PHP collection PHP and mysql

Escape character is a special character constant. Escape characters are backslashed " & quot; At the beginning, followed by one or more characters. The escaped character has a specific meaning, which is different from the original meaning of the character, so it is called "escaped" character. The use of escape characters 1: turn ordinary characters into special purposes, such as back key and enter key. 2. Used to convert a character with special meaning back to its original meaning. 3. Before data is written into the database, escape characters (function …
👁 180
mysqli in PHP

mysqli in PHP Language Notes PHP PHP collection PHP and mysql

The `mysqli_num_rows()` function is exclusively used with `SELECT` query methods, whereas the `mysqli_affected_rows()` function returns the number of rows affected by the previous SQL statement across the entire database; this function is primarily used with `INSERT`, `UPDATE`, and `DELETE` operations.
👁 145

Recommended reading

Simple Financial and Tax Accounting Promotion Page Website Template – 1138

Simple Financial and Tax Accounting Promotion Page Website Template – 1138 Practical Collection Yiyou template

This EyouCMS template is designed as a simple promotional page for financial and tax accounting services. It features a strong marketing-oriented design, a compact and efficient layout, and effectively highlights the advantages of financial and tax services, pricing policies, and contact information. It serves as an excellent tool for financial and tax firms conducting Baidu PPC or landing page marketing campaigns. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 52
Responsive Rural Homestay Website Template 0291

Responsive Rural Homestay Website Template 0291 Practical Collection Yiyou template

This set of eyoucms responsive templates is suitable for the farmhouse and B&B industries. The design style is warm and natural, and can display the B&B environment, farmhouse features, guest room facilities and tourism services. It helps B&Bs and farmhouses attract tourists online and enhance brand awareness. Template display Installation instructions Website backend: /login.php Account: admin Password: admin Related articles Yiyou CMS installation FAQ summary Yiyou CMS (…
👁 48
(PC + WAP) pbootCMS Green Lift Website Template; Conveyor Belt Website Source Code Download – 0643

(PC + WAP) pbootCMS Green Lift Website Template; Conveyor Belt Website Source Code Download – 0643 Practical Collection pbootcms Template

This PbootCMS template is designed specifically for the elevator, conveyor belt, and material handling equipment industries. It features a clean, modern design and is compatible with both PC and WAP devices. The user-friendly interface is ideal for displaying mechanical equipment specifications, project examples, and technical documentation. This template enables machinery and equipment companies to quickly set up their branded official websites, optimize product information presentation, and increase the conversion rate of customer inquiries. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin...
👁 57
Responsive Geological Survey Fieldwork Unit Website Template 1139

Responsive Geological Survey Fieldwork Unit Website Template 1139 Practical Collection Yiyou template

An eYouCMS responsive website template designed for geological survey institutes and similar organizations. Its professional and sophisticated design effectively showcases survey results, technical expertise, project cases, and institutional functions. This template helps survey and design institutes establish an authoritative online presence and attract both government and corporate clients. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Common Questions About eYouCMS Installation...
👁 61
Responsive Precision Electronics Technology Website Template 0292

Responsive Precision Electronics Technology Website Template 0292 Practical Collection Yiyou template

An eyouCMS responsive website template designed for the precision electronics industry. Its modern, tech-driven design effectively showcases electronic products, R&D capabilities, manufacturing expertise, and industry applications. This template helps precision electronics companies showcase their brands online and attract industry clients. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for YououCMS | YououCMS...
👁 37
(Adaptive mobile version) English-language foreign trade ballet shoe website – PBootCMS template; Latin dance shoe website source code download – 0644

(Adaptive mobile version) English-language foreign trade ballet shoe website – PBootCMS template; Latin dance shoe website source code download – 0644 Practical Collection pbootcms Template

An English-language PbootCMS website template for export-oriented ballet and Latin dance shoes, compatible with both PC and WAP devices. Featuring a fashionable, international design style, this template is ideal for dance shoe manufacturers to showcase their product ranges and export advantages. It helps Chinese footwear manufacturers promote their brands in overseas markets and secure international orders. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4...
👁 38