2

HI folks ive been trying to figure out a problem that's been haunting me for some time now and original started this thread thread PHPExcel - How to replace text using preg_replace. I was going about this all the wrong way and Mark gave me some tips on where to start. I gave up this project as I was very clueless of how to even start a script for this.

What I am currently attempting is to bold text that are within HTML marker <B> and <Strong>. After spending some time studying Jquery and some javascript to help me with this. I am understanding that ill nee to write a script to find text with HTML markups <b></b> and <strong></strong>,and tell the javascript to bold that text using the following method:

$objRichText = new PHPExcel_RichText();
$objRichText->createText('This text is ');
$objBoldTextRun = $objRichText->createTextRun('bold');
$objBoldTextRun->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getCell('B1')->setValue($objRichText);

I would imagine that with Jquery I would use something like the event .find but not quite sure what the best way to approach something like this. This is honestly way beyond my level of comprehension but willing to give it a shot with some help.

Update updated code:

<?php
/** Error reporting */

/** PHPExcel */
require_once '../js/PHPExcel/Classes/PHPExcel.php';
// Set active sheet index to the first sheet, so Excel opens this as the first sheet

// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$rows=2;
$sheet=$objPHPExcel->getActiveSheet();
$wizard = new PHPExcel_Helper_HTML();
//Font Setting for the Support group title.
$Support_team = array('font'=> array('bold'=> true,'color' => array('rgb' => '4D4D4D'),'size'  => 22,'name'  => 'Arial'),'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER),);
//Font settings for the header cells only.
$headers = array('font'=> array('bold'=> true,'color' => array('rgb' => '4D4D4D'),'size'  => 12,'name'  => 'Arial'),'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER),);
//Border settings
$borders = array('borders' => array('inside'=> array('style' => PHPExcel_Style_Border::BORDER_THIN,'color' => array('argb' => '717171')),'outline' => array('style' => PHPExcel_Style_Border::BORDER_THIN,'color' => array('argb' => '717171'))));

//  SQl database connections
$db = mysql_connect("localhost", "IMC_Admin", "IMCisgreat2014");
    mysql_select_db("imc_directory_tool",$db);
    $sql="select client,team_name,support_team_prime,prime_comments,support_team_backup,backup_comments,escalation1,escalation1_comments,escalation2,escalation2_comments,escalation3,escalation3_comments,escalation4,escalation4_comments,note from tbl_address ORDER BY team_name";
    $result=mysql_query($sql);
        $numrows=mysql_num_rows($result);
        if ($numrows>0)
        {
            while($data=mysql_fetch_array($result))
            {
//Cell Wraptext
$sheet->getStyle('C'.($rows+1).':D'.($rows+1))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+3).':D'.($rows+3))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+4).':D'.($rows+4))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+6).':D'.($rows+6))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+7).':D'.($rows+7))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+8).':D'.($rows+8))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+9).':D'.($rows+9))->getAlignment()->setWrapText(true);
$sheet->getStyle('B'.($rows+11).':D'.($rows+11))->getAlignment()->setWrapText(true);


$richTextClient = $wizard->toRichTextObject($data['client']);
$richTextteam_name = $wizard->toRichTextObject($data['team_name']);
$richTextsupport_team_prime = $wizard->toRichTextObject($data['support_team_prime']);
$richTextprime_comments = $wizard->toRichTextObject($data['prime_comments']);
$richTextsupport_team_backup = $wizard->toRichTextObject($data['support_team_backup']);
$richTextbackup_comments = $wizard->toRichTextObject($data['backup_comments']);
$richTextescalation1 = $wizard->toRichTextObject($data['escalation1']);
$richTextescalation1_comments = $wizard->toRichTextObject($data['escalation1_comments']);
$richTextescalation2 = $wizard->toRichTextObject($data['escalation2']);
$richTextescalation2_comments = $wizard->toRichTextObject($data['escalation2_comments']);
$richTextescalation3 = $wizard->toRichTextObject($data['escalation3']);
$richTextescalation3_comments = $wizard->toRichTextObject($data['escalation3_comments']);
$richTextescalation4 = $wizard->toRichTextObject($data['escalation4']);
$richTextescalation4_comments = $wizard->toRichTextObject($data['escalation4_comments']);
$richTextNote = $wizard->toRichTextObject($data['note']);

//This section is the actual data imported from the SQL database *don't touch*
$objPHPExcel->setActiveSheetIndex(0)              
->setCellValue('C'.($rows+1),$richTextClient) //this will give cell C2. 
->setCellValue('B'.$rows,$richTextteam_name) // this will give cell B2 
->setCellValue('C'.($rows+3),$richTextsupport_team_prime) //this will give C5 
->setCellValue('D'.($rows+3),$richTextprime_comments)  // This will give D5
->setCellValue('C'.($rows+4),$richTextsupport_team_backup)  //This will give C6
->setCellValue('D'.($rows+4),$richTextbackup_comments) //This will give D6  
->setCellValue('C'.($rows+6),$richTextescalation1)//THis will give you C8
->setCellValue('D'.($rows+6),$richTextescalation1_comments)//This will give you D8
->setCellValue('C'.($rows+7),$richTextescalation2)//This will give you C9
->setCellValue('D'.($rows+7),$richTextescalation2_comments)//This will give you D9
->setCellValue('C'.($rows+8),$richTextescalation3)//This will give you C10
->setCellValue('D'.($rows+8),$richTextescalation3_comments)//This will give you D10
->setCellValue('C'.($rows+9),$richTextescalation4)//This will give you C11
->setCellValue('D'.($rows+9),$richTextescalation4_comments)//This will give you D11
->setCellValue('B'.($rows+11),$richTextNote); //This will give you B13  

//Cell Merging 
$sheet
->mergeCells('B'.$rows.':D'.$rows)  
->mergeCells('B'.($rows+2).':D'.($rows+2))  
->mergeCells('B'.($rows+5).':D'.($rows+5))  
->mergeCells('B'.($rows+10).':D'.($rows+10))  
->mergeCells('C'.($rows+1).':D'.($rows+1))
->mergeCells('B'.($rows+11).':D'.($rows+11)); 

// Add some data  
$objPHPExcel->setActiveSheetIndex(0)  
->setCellValue('B'.($rows+1), 'Client:')
->setCellValue('B'.($rows+2), 'Support group contacts')     
->setCellValue('B'.($rows+3), 'Prime:')
->setCellValue('B'.($rows+4), 'Backup:')
->setCellValue('B'.($rows+5), 'Escalations') 
->setCellValue('B'.($rows+6), 'Escalation 1:') 
->setCellValue('B'.($rows+7), 'Escalation 2:') 
->setCellValue('B'.($rows+8), 'Escalation 3:') 
->setCellValue('B'.($rows+9), 'Escalation 4:') 
->setCellValue('B'.($rows+10), 'Notes'); 

//Format the hardcoded text 
$sheet->getStyle('B'.$rows)->applyFromArray($Support_team);
$sheet->getStyle('B'.($rows+2))->applyFromArray($headers);      
$sheet->getStyle('B'.($rows+5))->applyFromArray($headers);  
$sheet->getStyle('B'.($rows+10))->applyFromArray($headers); 

//Row height adjustments
$sheet->getRowDimension($rows+3)->setRowHeight(60);
$sheet->getRowDimension($rows+4)->setRowHeight(60);
$sheet->getRowDimension($rows+6)->setRowHeight(60);
$sheet->getRowDimension($rows+7)->setRowHeight(60);
$sheet->getRowDimension($rows+8)->setRowHeight(60);
$sheet->getRowDimension($rows+9)->setRowHeight(60);
$sheet->getRowDimension($rows+11)->setRowHeight(100);   


//Background color on cells 
$sheet->getStyle('B'.$rows.':D'.$rows)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+2).':D'.($rows+2))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+5).':D'.($rows+5))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+10).':D'.($rows+10))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+1))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+3))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+4))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+6))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+7))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+8))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+9))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');         

//Border range  
$sheet->getStyle('B'.$rows.':D'.($rows+11))->applyFromArray($borders);  
$rows+=14;
}
}

//This is the hard coded *non dynamic* cell formatting
    $sheet->getColumnDimension('A')->setWidth(5);
    $sheet->getColumnDimension('B')->setWidth(15);
    $sheet->getColumnDimension('C')->setWidth(50);
    $sheet->getColumnDimension('D')->setWidth(50);
    $sheet->getSheetView()->setZoomScale(90);
    $sheet->getStyle('A:D') ->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

// Rename sheet  
$sheet->setTitle('Directory Tool Full dump');

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

// Redirect output to a client’s web browser (Excel2007) 
$today=date("F.d.Y");
$filename = "Directory_Export-$today.xlsx";
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=$filename");
header("Cache-Control: max-age=0");
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');   
$objWriter->save('php://output');  
exit;  
?>
Community
  • 1
  • 1
Daniel Ellison
  • 1,339
  • 4
  • 27
  • 49

1 Answers1

0

If you're using the latest develop branch from the PHPExcel github repo, there is actually an html to rich text helper class:

The file 42richText.php in the Examples folder demonstrates its use:

$html1='<font color="#0000ff">
<h1 align="center">My very first example of rich text<br />generated from html markup</h1>
<p>
<font size="14" COLOR="rgb(0,255,128)">
<b>This block</b> contains an <i>italicized</i> word;
while this block uses an <u>underline</u>.
</font>
</p>
<p align="right"><font size="9" color="red">
I want to eat <ins><del>healthy food</del><strong>pizza</strong></ins>.
</font>
';

$html2='<p>
<font color="#ff0000">
    100&deg;C is a hot temperature
</font>
<br>
<font color="#0080ff">
    10&deg;F is cold
</font>
</p>';

$html3='2<sup>3</sup> equals 8';

$html4='H<sub>2</sub>SO<sub>4</sub> is the chemical formula for Sulphuric acid';


$wizard = new PHPExcel_Helper_HTML;
$richText = $wizard->toRichTextObject($html1);

$objPHPExcel->setActiveSheetIndex(0)
    ->setCellValue('A1', $richText);

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(48);
$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getStyle('A1')
    ->getAlignment()
    ->setWrapText(true);

$richText = $wizard->toRichTextObject($html2);

$objPHPExcel->setActiveSheetIndex(0)
    ->setCellValue('A2', $richText);

$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getStyle('A2')
    ->getAlignment()
    ->setWrapText(true);

$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A3', $wizard->toRichTextObject($html3));

$objPHPExcel->setActiveSheetIndex(0)
    ->setCellValue('A4', $wizard->toRichTextObject($html4));
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • Really appreciate this Mark, I knew I had to parse my data somehow but wasent picturing it. This should help me get back on track. Im gonna give this a try and report back. – Daniel Ellison Feb 18 '15 at 00:35
  • Hi Mark, I updated my code but now getting a blank screen. I updated my original post with the full code. I have my data taken from a mysql database so im trying to figure out how to implement the html class into my code. Im not sure what it is im screwing up at this point. Would you be able to help me out, I would really appreciate. – Daniel Ellison Feb 18 '15 at 03:12
  • Enable logging and here is the error im getting. Deprecated: `mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\inetpub\wwwroot\IMC Tools\IMC_Directory_Tool\staff\export\Full_Export.php on line 43 Fatal error: Cannot use object of type PHPExcel_RichText as array in C:\inetpub\wwwroot\IMC Tools\IMC_Directory_Tool\staff\export\Full_Export.php on line 122 ` – Daniel Ellison Feb 18 '15 at 04:10
  • [About your first error](http://stackoverflow.com/questions/13944956/the-mysql-extension-is-deprecated-and-will-be-removed-in-the-future-use-mysqli) – Mark Baker Feb 18 '15 at 07:39
  • As for the second error, `while($data=mysql_fetch_array($result))`... so data is an array comprising an entry for each column of your database row (client, team_name, support_team, etc), while `toRichTextObject()` expects a string as input – Mark Baker Feb 18 '15 at 07:40
  • You'd need to call with (for example) `$richTextClient = $wizard->toRichTextObject($data['client']);` – Mark Baker Feb 18 '15 at 07:46
  • Thanks Mark, still having no luck and getting error: `Fatal error: Cannot use object of type PHPExcel_RichText as array in C:\inetpub\wwwroot\IMC Tools\IMC_Directory_Tool\staff\export\Full_Export.php on line 138` I updated my original post with the code. Note quite how I am suppose to call out the data I currently have `->setCellValue('C'.($rows+1), ($richTextClient['client']))` would you have any more suggestions? – Daniel Ellison Feb 18 '15 at 11:14
  • I believe the issue was with the array `->setCellValue('C'.($rows+1), ($richTextClient['client']))` I changed this to `->setCellValue('C'.($rows+1), ($richTextClient->client))`. Now getting a different error: `Notice: Undefined property: PHPExcel_RichText::$client in C:\inetpub\wwwroot\IMC Tools\IMC_Directory_Tool\staff\export\Full_Export.php on line 128`. updated the original post with the updated code, would you have any suggestions? – Daniel Ellison Feb 18 '15 at 21:23
  • Ok so I removed the PHP errors and warnings and now I get my excel file and formatting is there but no data. Ill continue digging. – Daniel Ellison Feb 18 '15 at 21:31
  • `$richTextClient` not `$richTextClient->client` - the Rich Text object doesn't have a property of `client` - nor `$richTextClient['client']` - the Rich Text object isn't an array. The wizard takes a string value (not an array or object) and returns a Rich Text object that can then be set as a cell value.... in my example, `$richText = $wizard->toRichTextObject($html1);` takes a string argument (`$html1`) and converts it to a Rich Text object (`$richText`), then `$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $richText);` sets that __Rich Text object__ as the value to store in cell A1 – Mark Baker Feb 18 '15 at 23:01
  • Thanks Marc, i had tried that and now im getting corrupted excel files. the excel file down but i get warning the file seems corrupted continue? If i try opening it its just a blank excel file. Ill have to look at the code again but having no luck at all getting thos to work. – Daniel Ellison Feb 18 '15 at 23:31
  • Open it in a text editor and see if there are any leading/trailing spaces, BOM headings, obvious plaintext error messages, etc – Mark Baker Feb 18 '15 at 23:33
  • From a notepad i dont see any trailing spaces but do see that at least the title and workshett properties seem okay but not seeing any actual data. Alot of it is just random gibberish characters. im taking another look at the code – Daniel Ellison Feb 19 '15 at 00:46
  • I think I just found the issue, i think I may have overlooked the variable name and forgot to but capitals and lower cases where they need to be. Going trough the rest of my code. – Daniel Ellison Feb 19 '15 at 00:54
  • Well I fixed my variables and now I can see data on the excel but formatting and placements of the values are gone and there are alot of gibberish characters. What confuses me the most if that if I turn off error reporting I only get a blank excel sheet. If I put it back I get data but with radom characters everywhere. – Daniel Ellison Feb 19 '15 at 01:10
  • Got another clue i just found an error in the excel sheet. `Warning: unpack(): Type C: not enough input, need 1, have 0 in C:\inetpub\wwwroot\IMC Tools\IMC_Directory_Tool\staff\js\PHPExcel\Classes\PHPExcel\Writer\Excel5\Workbook.php on line 1314` – Daniel Ellison Feb 19 '15 at 01:18
  • Alright I got it fixed, I believe that the cause of this was several things. 1, I screwed up my variables where a letter was in capital and in other place it wasent. 2. There seemed to be permission issues as well as per some errors I was noticing, I allowed read/write permission to all sub directories. 3. To finally resolve my problem I had to switch from Excel5 to Excel2007 to get this to work properly. Now everything is as it should and I am very happy. Thank you for putting up with me Mark, if I may just one more question. What are the limitations for PHPExcel_Helper_HTML? – Daniel Ellison Feb 19 '15 at 03:16
  • To expand on my question, I want to know if you have had a chance to write documentation about the PHPExcel_Helper_HTML class. I just want to know what it supports in term of HTML, I noticed that it also strips unsupported HTML which is amazing. – Daniel Ellison Feb 19 '15 at 03:18
  • The HTML helper is very limited, and only supports a few basic tags like `
    `, ``, ``, ``, ``, ``, ``, etc... It doesn't support inline styling or stylesheets, not table data. If you look at the code, you can see the list or supported tags.... anything that isn't supported is stripped, though the content text should remain intact and simply "spaced" to ensure that words don't run into each other.
    – Mark Baker Feb 19 '15 at 08:57
  • It's pretty new code, I only wrote it over the period between Christmas and New Year, and it isn't documented other than the example to demonstrate its use – Mark Baker Feb 19 '15 at 08:59