设置自动调整大小列phpExcel

时间:2014-01-22 14:56:06

标签: php phpexcel

如何让PHPExcel自动创建列宽我不喜欢手动进入并拉伸列。我看了其他的例子,但没有一个适合我。这是我的代码:

$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', "Company Name");
$objPHPExcel->getActiveSheet()->setCellValue('B1', "Company Type");
$objPHPExcel->getActiveSheet()->setCellValue('C1', "First Name");
$objPHPExcel->getActiveSheet()->setCellValue('D1', "Last Name");
$objPHPExcel->getActiveSheet()->setCellValue('E1', "Position");
$objPHPExcel->getActiveSheet()->setCellValue('F1', "Email");

// Set outline levels

$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setOutlineLevel(1)
                                                       ->setVisible(false)
                                                       ->setCollapsed(true);

// Freeze panes

$objPHPExcel->getActiveSheet()->freezePane('A2');


// Rows to repeat at top

$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);




try {

    $stmt3 = $DB->prepare('SELECT * FROM companies C INNER JOIN personalInfo PI ON C.CompanyName = PI.Company_id');
    $stmt3->execute();


} catch(PDOException $e) {  
    echo $e->getMessage();  
}

$info3 = $stmt3->fetchAll();


$i = 2;
foreach($info3 as $info) {
    $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $info['CompanyName'])
                                  ->setCellValue('B' . $i, $info['CompanyType'])
                                  ->setCellValue('C' . $i, $info['firstName'])
                                  ->setCellValue('D' . $i, $info['lastName'])
                                  ->setCellValue('E' . $i, $info['position'])
                                  ->setCellValue('F' . $i, $info['email']);
    $i++;
}


// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);


// Save Excel 2007 file

$callStartTime = microtime(true);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;

echo "Excel file has been created click <a href='Excel.xlsx'>HERE</a> to view it.";

3 个答案:

答案 0 :(得分:41)

如开发人员文档第4.6.28节所述,标题为Setting a column's width

$objPHPExcel->getActiveSheet()
    ->getColumnDimension('A')
    ->setAutoSize(true);

必须为每列单独设置,因此要为所有列A到F设置它,请使用循环

for($col = 'A'; $col !== 'G'; $col++) {
    $objPHPExcel->getActiveSheet()
        ->getColumnDimension($col)
        ->setAutoSize(true);
}

答案 1 :(得分:18)

    $nCols = 6; //set the number of columns

    foreach (range(0, $nCols) as $col) {
        $objPHPExcel->getActiveSheet()->getColumnDimensionByColumn($col)->setAutoSize(true);                
    }

答案 2 :(得分:0)

foreach(range('A','G') as $columnID)
{
    $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}