【发布时间】:2019-01-03 21:54:33
【问题描述】:
我目前正在使用 PHPExcel 将订单信息输出到 Excel。
我有以下 foreach 语句最终生成我的数据,例如下订单的城市、餐厅名称等。
请原谅嵌套的 foreach 循环 - 这是我可以嵌套在所有城市、法律实体和餐馆中以生成客户想要的数据的唯一方法。
使用发布的答案here 动态生成行和列整数,我在我的代码中进行了尝试。
$row = 1; // 1-based index
$col = 0;
foreach ($this->data['total_by_city'] as $city_id => $total_city){
$city_name = '';
foreach ($this->data['total_by_legal_entities'] as $legal_entity_id => $total_legal_entity) {
$legal_entity_name = '';
foreach ($this->data['restaurant_by_legal_entities'][$legal_entity_id] as $restaurant_id) {
$orders = $this->data['order_by_restaurants'][$restaurant_id];
$restaurant_name = '';
if ($orders)
{
foreach ($orders as $order_id => $order)
{
$restaurant_name = $order['restaurant_name'];
$legal_entity_name = $order['legal_entity'];
$city_name = $order['city'];
echo $row . ", ". $col . "<br>";
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $order['city']);
$col++;
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $order['legal_entity']);
$col++;
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $order['restaurant_name']);
$col++;
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $order['payment_method']);
$col++;
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $order['order_number']);
$col++;
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $order['date_created']);
$col++;
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $order['customer_name']);
$col++;
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $order['order_type']);
$col++;
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $order['amount']);
$row++;
echo $row . ", ". $col . "<br>";
$col = 0;
}
}
}
}
}
当我运行代码并尝试打开 .xlsx 文件时,我在 Excel 中收到“损坏的 Excel 电子表格”错误。
为了确保我的行和列(分别)索引正确,我将它们打印出来:
1, 0
2, 8
2, 0
3, 8
3, 0
4, 8
4, 0
5, 8
5, 0
6, 8
6, 0
7, 8
7, 0
8, 8
8, 0
9, 8
9, 0
10, 8
10, 0
11, 8
11, 0
12, 8
12, 0
13, 8
13, 0
14, 8
14, 0
15, 8
15, 0
16, 8
从该观察中,我发现我使用的行和列索引不正确。它们都位于错误的位置,并且重置/增量不正确。
我的问题是 - 如何正确增加和重置列和行索引?
【问题讨论】:
-
... 或查看stackoverflow.com/a/37972341/4719732 将索引值转换为列字母。我不知道哪种方式更快......