基本上我需要获取这些SQL数据并让它为每个用户创建一个包含不同工作表名称的工作簿以及属于该用户的数据。所以Smith_Joe会有一张名为Smith_Joe的表格,在那张表格中会显示他的信息。这是sql数据:
TeamName UserID Deparment Description
---------------------------------------------------
Smith_Joe JOE4S 52200 Sales
Smith_Joe JOE4S 53002 Budget
Smith_Joe JOE4S 43302 Dev
Black_BJ BJ3OO 43332 Mrkt
Steh_Tray ST44S 65573 Prod
Steh_Tray ST44S 52200 Sales
到目前为止,我没有太多运气,但这是我到目前为止的代码:
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
$tn = $row['TeamName'];
$userid = $row['UserID'];
$dep = $row['Departments'];
$des = $row['Description'];
$objWorksheet = new PHPExcel_Worksheet($objPHPExcel);
$objPHPExcel->addSheet($objWorksheet);
$objWorksheet->setTitle(''. $tn);
$objWorksheet->setCellValue('A2' , $tn);
$objWorksheet->setCellValue('B2' , $userid);
$objWorksheet->setCellValue('C2', $dep);
$objWorksheet->setCellValue('D2' , $des);
我得到的问题是我得到了所有带有名字的工作表,但每一行都列在不同的工作表上。所以对于上面代码的示例。我得到了Smith_Joe 3张,每张一张。 Black_BJ获得一张,Steh_Tray获得2张。他们都应该只有一张纸,上面有所有信息。
答案 0 :(得分:2)
点击
$objWorksheet = new PHPExcel_Worksheet($objPHPExcel);
$objPHPExcel->addSheet($objWorksheet);
$objWorksheet->setTitle(''. $tn);
在while循环之外。由于这个
,每一行都会获得一张新表答案 1 :(得分:0)
您可以先选择不同的团队名称,然后在SQL查询中预设团队名称,从表格中选择数据并写入工作表,例如。
// write query to select distinct TeamName here
$stmt = ...sql query select distinct TeamName from table
// Then loop through
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$tn = $row['TeamName'];
$objWorksheet = new PHPExcel_Worksheet($objPHPExcel);
$objPHPExcel->addSheet($objWorksheet);
$objWorksheet->setTitle(''. $tn);
// then select all results for that TeamName
$stmt2 = ... sql query select results where TeamName=$tn
// then for each row returned write to file
$i = 2; // set row iterator
while($row2 = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC))
{
$userid = $row2['UserID'];
$dep = $row2['Departments'];
$des = $row2['Description'];
$objWorksheet->setCellValue('A' . $i , $tn);
$objWorksheet->setCellValue('B' . $i , $userid);
$objWorksheet->setCellValue('C' . $i, $dep);
$objWorksheet->setCellValue('D' . $i , $des);
$i++;
}
}