Duplicating cells content when saving to Excel2007 file

Topics: Developer Forum, User Forum
Oct 5, 2013 at 6:11 PM
So, I have a small script, which takes xls/xlsx file, scans it for keywords, highlights them and then dumps content into xlsx file.

The problem is when I open resulting file, I have duplicated values in cells so if cell has content "Test" it would be "TestTest".

I tried switching from Excel2007 to Excel5 export and that partially fixed the problem: duplication of content had gone, but after a some point data is becoming an unreadable mix of unicode characters like that: 㼀䀄㠄䀄㸄㐄㴄㸄㌄㸄 䈀㸄㼄㬄㠄㈄〄 㸀㄄㔄䤄〄丄䈄 ㌀〄㜄㠄䐄㠄䘄㠄䀄㸄㈄〄䈄䰄⸄ ᨀ㸄㰄㰄㔄㴄䈄〄䀄㠄㤄 ㌀㔄㴄㔄䀄〄㬄䰄㴄㸄㌄㸄 㐀㠄䀄㔄㨄䈄㸄䀄〄 ḀḄḄ ∀ጀ〄㜄㼄䀄㸄㰄 㰀㔄㘄䀄㔄㌄㠄㸄㴄

The way I manage files:
$reader   = PHPExcel_IOFactory::createReader($filetype);
$phpexcel = $reader->load($this->inputFile);
$sheet    = $phpexcel->getActiveSheet();
$regex = '/\b(' . implode('|', $this->keywords) . ')/ui';

for ($row = 1; $row <= $maxRow; $row++) {
    for ($col = 0; $col <= $maxCol; $col++) {
      $text     = $sheet->getCellByColumnAndRow($col, $row)->getFormattedValue();
      $tokens   = preg_split($regex, $text, -1, PREG_SPLIT_DELIM_CAPTURE);
      $richtext = $this->formatTokens($tokens);
      $sheet    = $sheet->setCellValueByColumnAndRow($col, $row, $richtext);

$writer = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel2007');
The highlighting function:
function formatTokens($tokens) {
      $richtext = new PHPExcel_RichText();
      foreach($tokens as $token) {
        $coloredText = $richtext->createTextRun($token);
        if (in_array($token, $this->keywords)) {
          $coloredText->getFont()->setColor(new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_DARKRED));
        else {
          $coloredText->getFont()->setColor(new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK));
      return $richtext;
Any help would be highly appreciated.