php+sqlsrv导出复杂表头的excel

打印的表头已经处理好的

clipboard.png
导出的时候不能按格式顺利的输出

$sql = "select row_number() over (order by id desc ) as rownum
   ,[companyname],isnull(dbo.get_IdToValue(unitprop),'')  as [unitprop], isnull(dbo.get_IdToValue(unitspec),'') as [unitspec], isnull(dbo.get_IdToValue(fundspychannels),'')   [fundspychannels],[officepostnum] ,[staffnum],[retirednum],[availcar],[scrapcar], [quotacar],[dbnum], isnull(dbo.get_IdToValue(brand),'')  [brand], isnull(dbo.get_IdToValue(cartype),'')  as [cartype],isnull(dbo.get_IdToValue(output),'')  as [output],isnull(dbo.get_IdToValue(seats),'')  as [seats],[oneprice],[num],[price],[appurchrate],[totalprice],isnull(dbo.get_IdToValue(afundfrom),'')  as [afundfrom]
  ,isnull(dbo.get_IdToValue(abuytype),'')  as [abuytype],[acaruse],[areason],[auditopn],[auditorname],CONVERT(varchar(100), auditime, 23) as [auditime]
  , (case when auditflag = 0 then '未审核' when auditflag =1 then '不同意' when auditflag=2 then '同意' end ) as auditflag
  ,[approveopn],[approver]
  ,(case when approveflag = 0 then '未审批' when approveflag =1 then '不同意' when approveflag=2 then '同意' end ) as approveflag,CONVERT(varchar(100), approvetime, 23) as [approvetime],[acfzrname],[managername],[magtel]
  ,(select manname from t_account where acid=V_applypurchasecar.acid) as operator,[remark],CONVERT(varchar(100), applydate, 23) as [applydate],CONVERT(varchar(100), created, 23) as created  from V_applypurchasecar";
if ($where != "") {
    $sql = $sql . " where " . $where;
}
$result = $db->query($sql);
//$title  = "序号\t申购单位名称\t单位规格\t单位性质\t经费供应渠道\t厅级职数\t人员编制\t离退休干部数\t编制车数\t现有车辆数\t应报废数\t定编文号\t申购车辆类型\t种类\t排量\t座位数\t单价\t数量\t金额(万元)\t购置费(万元)\t经费合计(万元)\t购车资金来源\t购置方式\t用途\t申购理由\t主管部门意见\t负责人姓名\t审核时间\t审核结果\t审批意见\t审批人\t审批结果\t审批时间\t申购单位负责人\t经办人\t联系电话\t录入人员\t备注\t申报时间\t录入时间";
$title = "<table id='tb' name='tb' class='ptbiankuang' width='100%' border='0' cellspacing='0' cellpadding='0' style='margin-top:-1px;'>
          <tr style='height:36pt;'>
          </tr>
          <tr style='height:36pt;'>
           <th rowspan=2>序号</th>
           <th rowspan=2>单位</th>
           <th colspan=6>机关有关情况</th>
           <th colspan=3>现有车辆情况</th>
           <th colspan=7>申购车辆情况</th>
           <th rowspan=2>备注</th>
          </tr>
          <tr style='height:36pt;'>
           <th>规格</th>
           <th>性质</th>
           <th>资金供应渠道</th>
           <th>领导职数</th>
           <th>人员编制</th>
           <th>离退休干部数</th>
           <th>编制车数</th>
           <th>实有车数</th>
           <th>应报废车辆数</th>
           <th>厂牌型号</th>
           <th>种类</th>       
           <th>排量或座位数</th>
           <th>数量</th>
           <th>单价</th>
           <th>经费合计</th>
           <th>经费来源</th>                       
          </tr></table>";

$fn     = saveexcelfile($title, $result);
echo $fn;
freedbquerystmt($result);
exit;

之前的简单的表头,可以按格式导出,现在把title换了之后,不太好使

function saveexcelfile($titles,$stmt)
{
    $titles=iconv("UTF-8", "GBK", $titles);
$str = '';
$numFields = sqlsrv_num_fields( $stmt );

while(  $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_BOTH))
{
     /* Iterate through the fields of each row. */
     $rowstr="";
     for($i = 0; $i < $numFields; $i++)
     {
    
          $cols=$row[$i];
           if($rowstr=="")
         {
              //  $rowstr=$cols;
              $rowstr=iconv("UTF-8", "GBK", $cols);
         }else{
           //$rowstr=$rowstr."\t".$cols;
           $rowstr=$rowstr."\t".iconv("UTF-8", "GBK", $cols);
         }
     }
      $str.=$rowstr.PHP_EOL;
}
$str=$titles. PHP_EOL .$str;
$fn=date("YmdHis").rand(100,999).".xls";

    $path="download/".$fn;
ob_end_clean();
header("Content-type: text/html; charset=utf-8");

 if($f  = file_put_contents($path, $str,FILE_APPEND)){// 这个函数支持版本(PHP 5) 
  return $path;
 }else{
     return "error";
 }

}

表格导出函数是之前封装好的。
title该如何修改呢?

阅读 2.3k
2 个回答
首先我们要引入导出的类:require_once dirname(__FILE__) . '/Classes/PHPExcelCore.php';
然后需要我们把表头放在一个数组中:
$date = date('Y-m-d');
    $title = array(
           array('value' => "公务用车申购审批呈报表",'col' => 19,'row' => 3,
               'children' =>
                   array(
                       array('value' => '日期:'.$date,'col' => 2,'row' => 1,
                           'children' =>
                               array(
                                   array('value' => '序号','col' => 1,'row' => 3,'width' => 20),
                                   array('value' => '单位','col' => 1,'row' => 3,'width' => 25),
                                   array('value' => '单位有关情况','col' => 6,'row' => 1,
                                       'children' =>
                                           array(
                                               array('value' => '规格','col' => 1,'row' => 2),
                                               array('value' => '性质','col' => 1,'row' => 2),
                                               array('value' => '经费供应渠道','col' => 1,'row' => 2,'width' => 25),
                                               array('value' => '领导职数','col' => 1,'row' => 2,'width' => 25),
                                               array('value' => '人员编制','col' => 1,'row' => 2,'width' => 25,),
                                               array('value' => '离退休干部数','col' => 1,'row' => 2,'width' => 25)
                                           )
                                   ),
                                   array('value' => '现有车辆情况','col' => 2,'row' => 1,
                                       'children' =>
                                           array(
                                               array('value' => '编制车数','col' => 1,'row' => 2,'width' => 25),
                                               array('value' => '实有车数','col' => 1,'row' => 2,'width' => 25),
                                               /*array('value' => '应报废车辆数','col' => 1,'row' => 2,'width' => 25)*/
                                           )
                                   ),
                                   array('value' => '申购车辆情况','col' => 7,'row' => 1,
                                       'children' =>
                                           array(
                                               array('value' => '厂牌型号','col' => 1,'row' => 2,'width' => 25),
                                               array('value' => '车辆类型','col' => 1,'row' => 2,'width' => 25),
                                               array('value' => '种类','col' => 1,'row' => 2,'width' => 20),
                                               array('value' => '排量或座位数','col' => 1,'row' => 2,'width' => 20),
                                               array('value' => '数量','col' => 1,'row' => 2,'width' => 20),
                                               array('value' => '单价','col' => 1,'row' => 2,'width' => 20),
                                               /*array('value' => '购置税','col' => 1,'row' => 2),
                                               array('value' => '经费合计','col' => 1,'row' => 2,'width' => 25),*/
                                               array('value' => '经费来源','col' => 1,'row' => 2,'width' => 25)
                                           )
                                   ),
                                   array('value' => '备注','col' => 1,'row' => 3)
                               )
                       ),
                       array('value' => '','col' => 14),
                       array('value' => '金额单位:万元','col' => 2),
               )
           )
   );
    $arr = array();
    $data = array();
    $oneprice = 0;
    $oneprice1 = '';
    $num = 0;
    $appurchrate = 0;
    $price = 0;
    while ($row = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC)) {
   //转化厂牌型号
   $row['brandname'] = getBrandSystem($row['brand'],1,$db);
   $row['systemname'] = getBrandSystem($row['systemid'],2,$db);


//        $row['brandname']=$row['brand']==0?'无':getbrand($row['brand'],$db);
//        if(positive_integer($row['systemid'])){
//            $row['systemname']=getsystem($row['systemid'],$db);
//        }else{
//            $row['systemname']=$row['systemid']=='0'?'无':$row['systemid'];
//        }
   $arr['rownum'] = $row['rownum'];
   $arr['companyname'] = $row['companyname'];
   $arr['unitspec'] = $row['unitspec'];
   $arr['unitprop'] = $row['unitprop'];
   $arr['fundspychannels'] = $row['fundspychannels'];
   if (!empty($row['officepostnum']))
   {
       $arr['officepostnum'] = $row['officepostnum'];
   }
   else
   {
       $arr['officepostnum'] = '';
   }
   if (!empty($row['staffnum']))
   {
       $arr['staffnum'] = $row['staffnum'];
   }
   else
   {
       $arr['staffnum'] = '';
   }
   if (!empty($row['retirednum']))
   {
       $arr['retirednum'] = $row['retirednum'];
   }
   else
   {
       $arr['retirednum'] = '';
   }
   if (!empty($row['quotacar']))
   {
       $arr['quotacar'] = $row['quotacar'];
   }
   else
   {
       $arr['quotacar'] = '';
   }
   if (!empty($row['availcar']))
   {
       $arr['availcar'] = $row['availcar'];
   }
   else
   {
       $arr['availcar'] = '';
   }
   /*if (!empty($row['scrapcar']))
   {
       $arr['scrapcar'] = $row['scrapcar'];
   }
   else
   {
       $arr['scrapcar'] = '';
   }*/
   if (!empty($row['brandname']) && !empty($row['systemname'])){
       $arr['brand'] = $row['brandname']."-".$row['systemname'];
   }else {
       $arr['brand'] = $row['brandname'].$row['systemname'];
   }
   $arr['carmodel'] = $row['carmodel'];
   $arr['cartype'] = $row['cartype'];
   if ($row["output"] &&  $row["seats"]) {
       $arr['output'] = "".$row["output"]."、".$row["seats"]."";
   } elseif (empty($row["seats"])){
       $arr['output'] = $row["output"];
   } else {
       $arr['output'] = $row["seats"];
   }
   $arr['num'] = $row['num'];
   $arr['oneprice'] = sprintf("%01.3f", $row["oneprice"]);
   /*$arr['appurchrate'] = sprintf("%01.3f", $row['appurchrate']);
   $arr['price'] = $row["num"]*($row["oneprice"]+$row['appurchrate']);*/
   $arr['afundfrom'] = $row['afundfrom'];
   $arr['remark'] = $row['remark'];
   $num += $row['num'];
   $price = sprintf("%01.3f", $row["oneprice"]);
   $oneprice += $price;
   $oneprice1 += $row["num"]*($row["oneprice"]);
   /*$appurchrate += $row['appurchrate'];
   $price += $row["num"]*($row["oneprice"]+$row['appurchrate']);*/
   array_push($data,$arr);
    }
    $lData = array('合计','','','','','','','','','','','','','',$num,'总金额:'.$oneprice1,'');
    array_push($data,$lData);
    $lData1 = array('初审意见:','','','','','','','审核意见:','','','','','审批意见:','','','','','');
    array_push($data,$lData1);
    $today = date('Y-m-d');
    $manname = $_SESSION['user']['manname'];
    $lData2 = array('','','','','','','','','','','','','','','','','制表人:',$manname);
    array_push($data,$lData2);
    $arrayLevel = arrayLevel($title);
    $phpExcelCore = new phpExcelCore();
    $fn = $phpExcelCore::RecursionCreateExecl($title,$data,$arrayLevel);
    echo $fn;
    freedbquerystmt($result);
    exit;

额,你还用这种方式,建议换excel 包吧 composer安装个就行

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题