使用php-xlswriter,实现一个功能,本功能第一步向数据表cardinfo表获取数据,第二步导出excel文件下载到本地下载
时间: 2024-03-31 22:34:51 浏览: 76
好的,我可以帮你解答。首先,你需要安装 php-xlswriter 扩展。安装方法可以参考 https://github.com/viest/php-ext-excel-export#installation。
接下来,你可以按照以下步骤实现你的功能:
1. 连接数据库
在 PHP 中连接数据库可以使用 PDO 或者 mysqli 等扩展。这里以 PDO 为例:
```
$dsn = 'mysql:host=localhost;dbname=your_database';
$username = 'your_username';
$password = 'your_password';
try {
$db = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
```
2. 获取数据
使用 PDO 查询数据可以这样:
```
$sql = 'SELECT * FROM cardinfo';
$stmt = $db->query($sql);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
```
3. 导出 Excel 文件
使用 php-xlswriter 导出 Excel 文件可以这样:
```
$writer = new XLSXWriter();
// 添加表头
$writer->writeSheetHeader('Sheet1', array_keys($rows[0]));
// 添加数据
foreach ($rows as $row) {
$writer->writeSheetRow('Sheet1', $row);
}
// 设置文件名和下载
$filename = 'cardinfo.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
$writer->writeToStdOut();
```
完整代码:
```
$dsn = 'mysql:host=localhost;dbname=your_database';
$username = 'your_username';
$password = 'your_password';
try {
$db = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = 'SELECT * FROM cardinfo';
$stmt = $db->query($sql);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$writer = new XLSXWriter();
// 添加表头
$writer->writeSheetHeader('Sheet1', array_keys($rows[0]));
// 添加数据
foreach ($rows as $row) {
$writer->writeSheetRow('Sheet1', $row);
}
// 设置文件名和下载
$filename = 'cardinfo.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
$writer->writeToStdOut();
```
你可以根据你的实际情况修改代码。希望能对你有所帮助。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![crx](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)