我正在尝试在单个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++;
}
答案 0 :(得分: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