PHPOffice / PHPExcel

ARCHIVED
Other
11.46k stars 4.19k forks source link

Modify Excel default formats using PHPExcel? #572

Open BrandonNoad opened 9 years ago

BrandonNoad commented 9 years ago

Hi,

I am running into the issue described here: https://superuser.com/questions/392528/why-does-pasting-into-an-unprotected-cell-in-excel-protect-it

Basically, a user pastes some content into an unlocked cell within a protected worksheet, and the cell ends up locked.

Is there a way to modify the default Excel formats using PHPExcel? I want to change the "Normal" format to be unlocked by default.

Thanks!

BrandonNoad commented 9 years ago

So I was able to modify the 'Normal' style by adding a few lines to the PHPExcel_Writer_Excel2007_Style::writeStyles() method

// cellStyleXfs
$objWriter->startElement('cellStyleXfs');
$objWriter->writeAttribute('count', 1);

    // xf
    $objWriter->startElement('xf');
        $objWriter->writeAttribute('numFmtId',  0);
        $objWriter->writeAttribute('fontId',    0);
        $objWriter->writeAttribute('fillId',    0);
        $objWriter->writeAttribute('borderId',  0);

        /*
         * modify the default 'Normal' cell style to turn OFF Protection => Locked
         * https://superuser.com/questions/392528/why-does-pasting-into-an-unprotected-cell-in-excel-protect-it
         */
        $objWriter->startElement('protection');
            $objWriter->writeAttribute('locked',    0);
        $objWriter->endElement();

    $objWriter->endElement();

$objWriter->endElement();

This change, however, didn't solve my problem. It seems, when you paste formatted text, the cell isn't given the 'Normal' style as described in the article. Instead, the cell gets the default workbook style, then the formatting is layered on top.

So, if I do the following:

$defaultWorkbookStyle = array(
    'protection' => array(
        'locked' => true
    )
);

$phpExcel->getDefaultStyle()->applyFromArray($defaultWorkbookStyle);

It solves my problem. However, I now how to explicitly lock any cells that I want to be locked inside the protected worksheets.