1

我正在尝试在一个 xlsx 文件中以正确的顺序导出数据。

下面的代码有效,但它将所有数据放入 xlsx 文件中。它几乎将我数据库中的所有数据按照当前在数据库中的任何顺序转储到电子表格中

eg.
ID  Name    Type    Amount
1   aaaa   Income   20
2   bbbb   Exped    30
3   cccc   Income   40

我想要做的是整理它并将相同的放在一起,例如。它在 excel 中应该是什么样子:

row1: ID    Name    Type    Amount
row2: INCOME
row3: 1     aaaa    Income  20
row4: 3     cccc    Income  40



row6: EXPENDITURE
row7: 2     bbbb    Exped   30

关于如何实现这一目标的任何想法?下面是我的代码。干杯,

/** Query 1.0 */
    $query = "SELECT * FROM financial";

    if ($result = mysql_query($query) or die(mysql_error())) {
/** Create a new PHPExcel object 1.0 */
   $objPHPExcel = new PHPExcel();
   $objPHPExcel->getActiveSheet()->setTitle('Data');
   }  

    /**HEADINGS*/
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'FINANCIAL_ID');
$objPHPExcel->getActiveSheet()->setCellValue('B1', 'TYPE');
$objPHPExcel->getActiveSheet()->setCellValue('C1', 'NAME');
$objPHPExcel->getActiveSheet()->setCellValue('D1', 'YEAR');
$objPHPExcel->getActiveSheet()->setCellValue('E1', 'AMOUNT');

/** Loop through the result set 1.0 */
    $rowNumber = 2; //start in cell 1
    while ($row = mysql_fetch_row($result)) {
       $col = 'A'; // start at column A
       foreach($row as $cell) {
          $objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
          $col++;
       }
       $rowNumber++;
}
4

1 回答 1

2

您可以获得所有类型的启动:

$query = "SELECT DISTINCT Type FROM financial";
$types = mysql_fetch_array($query);

然后遍历每种类型分别获取它们的数据:

foreach($types as $type){
    $query = "SELECT * FROM financial WHERE TYPE='$type'";
    while($row = mysql_fetch_row($query)){
        // Output your data into the spreadsheet
    }

    // Get the subtotal for each type.
    $query = "SELECT SUM(Amount) as total FROM financial WHERE Type='$type'";
    $result = mysql_fetch_array($query);
    $subtotal = $result['total'];
    // Add the subtotal to the spreadsheet

    $row += 5; // Skip a few rows in between if you want
}

// Get the Total for everything
$query = "SELECT SUM(Amount) as total FROM financial";
$result = mysql_fetch_array($query);
$total = $result['total'];
// Add the total to the spreadsheet
于 2013-10-16T04:16:16.867 回答