php - 动态字段 Excel 输出 PHP
问题描述
假设我在 SQL 数据库上有这张表:
+---------------+-----------------+-----------------+
| category | name | month |
+---------------+-----------------+-----------------+
| Fruit | Mango |January |
| Fruit | Apple |January |
| Fruit | Grape |February |
| Vegetable | Tommato |February |
| Vegetable | Cuccumber |March |
| Animal | Chicken |March |
+---------------+-----------------+-----------------+
然后我想使用 PHPExcel 动态输出一个 excel 文件,如下所示:
所以,因为它是动态的,所以每当数据库发生更新时,excel 输出就会跟随:SqlTable 更新:
+---------------+-----------------+-----------------+
| category | name | month |
+---------------+-----------------+-----------------+
| Fruit | Mango |January |
| Fruit | Apple |January |
| Fruit | Grape |February |
| Vegetable | Tommato |February |
| Vegetable | Cuccumber |March |
| Animal | Chicken |March |
| Vegetable | Onion |April |
| Animal | Fish |April |
+---------------+-----------------+-----------------+
使用 phpExcel 可以做到这一点吗?
我试过的:
public function excel()
{
$spreadsheet = new Spreadsheet();
$month = $this->db
->select('month')
->distinct('category,name')
->order_by('category,name')
->get('mytable')->result_array();
$data = $this->db
->select('category,name')
->order_by('category,name')
->get('mytable')->result_array();
$col_data = 'b';
$row_category = 1;
$row_name = 2;
foreach ($data as $d) {
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue($col_data.$row_category, $d['category']);
$sheet->setCellValue($col_data.$row_name, $d['name']);
$col_data++;
}
$col_month = 'a';
$row_month = 3;
foreach ($month as $m) {
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue($col_month.$row_month, $m['month']);
$row_month++;
}
$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');
}
结果是这样的:
请让我知道该怎么做
解决方案
推荐阅读
- selenium - 生成错误 ##[error]Error: The process 'C:\Program Files\dotnet\dotnet.exe' failed with exit code 1 Help Please
- reactjs - 在 Reactjs 中解压并渲染一个 pdf 文件
- repository - 是什么创建了未存储在数据库中的聚合?
- angular - 如何更改heroku的node.js buildpack以运行构建以外的脚本
- solidity - 以数组长度为条件循环数组
- c# - UWP 应用中的视频编辑
- asp.net-core - Application Insights 未记录 SQL 依赖项查询
- android - 通过意图或实例打开活动
- c++ - 如何将 c_void 发送到另一个线程
- twilio - 如何将来自美国的来电转接到 Twilio 中的菲律宾号码?