2013-10-16 112 views
1

我試圖在一個單一的xlsx文件中以正確的順序導出數據。PHPExcel導出excel的數據

下面的代碼工作,但它將所有數據放入一個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++; 
} 
+0

+1我不知道你能像這樣增加一個字符。很酷的東西 – immulatin

回答

1

你可以得到所有類型開始:

$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 
+0

yeap我已經做到了。收入將顯示沒有問題。它只是第二部分:支出將低於收入的小計,我不太確定如何把數據放在那裏。從這個代碼中,手動選擇了rownumber。我如何讓它選擇下一個可用/空行? – Tuzki

+0

因此,當您完成特定類型時,您正在尋找添加小計欄?那麼當你通過所有類型時,最後加上總數?不知道我完全理解。 – immulatin

+0

我可能會在稍後離開小計和總計。生病編輯問題 – Tuzki