简体   繁体   中英

Setting the column value by number in PHPExcel

I've got an array with specifications. I want each specification to become a column. I am having trouble with working this out though.

$specifications = new Specifications();
$columnCounter = 1;
foreach ($specifications as $specificationId => $specification) {
    $column = PHPExcel_Cell::getColumnByNumber($columnCounter);
    $objPHPExcel
        ->getActiveSheet()
        ->getColumnDimension($column)
        ->setAutoSize(true)
    ;

    $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue($column.'1', $specification['value'])
    ;

    $columnCounter++;
}

The PHPExcel::getColumnByNumber() is of course an imaginary function. Though I am wondering how others do this and how best to address this.

$book = new PHPExcel();
$book->setActiveSheetIndex(0);
$sheet = $book->getActiveSheet();
$sheet->setTitle('Sets');
$xls_row = 5;
$xls_col = 3;
foreach($specifications as $specificationId => &$specification)
{
  $adr = coord($xls_row, $xls_col);
  $sheet->setCellValueExplicit($adr, $specification->title, PHPExcel_Cell_DataType::TYPE_STRING);
  $sheet->getColumnDimension(coord_x($xls_col))->setAutoSize(true);
  $xls_col++;
}

// convert a 0-based coordinate value into EXCEL B1-format
function coord_x($x)
{
  if($x<26) $x = chr(ord('A')+$x);
  else
  {
    $x -= 26;
    $c1 = $x % 26;
    $c2 = intval(($x - $c1)/26);
    $x = chr(ord('A')+$c2).chr(ord('A')+$c1);
  }
  return $x;
}

// convert X,Y 0-based cell address into EXCEL B1-format pair
function coord($y,$x)
{
  return coord_x($x).($y+1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM