phpexcel-Set table font color background style, data format, alignment, add picture, annotation, text block, merge split cell, cell password protection ____php
First go to the phpexcel official website to download the latest phpexcel class. Next week, decompress a classes folder, which contains the folders of PHPExcel.php and PHPExcel. This class file and folder are what we need. Decompress the classes to your project. In a directory, the name is phpexcel, start myself, (the code is taken from its own example)
Program part
require_once './phpexcel/PHPExcel.php';
// First create a new object PHPExcel object
$ objPHPExcel = new PHPExcel ();
// Set some properties of the file, you can see these values in the xls file-> properties-> detailed information, these values are not in the xml table
$ objPHPExcel
-> getProperties () // Get the file properties object and provide setting resources for the following
-> setCreator ("Maarten Balliauw") // Set the creator of the file
-> setLastModifiedBy ("Maarten Balliauw") // Set the last modified
-> setTitle ("Office 2007 XLSX Test Document") // Set title
-> setSubject ("Office 2007 XLSX Test Document") // Set subject
-> setDescription ("Test document for Office 2007 XLSX, generated using PHP classes.") // Set note
-> setKeywords ("office 2007 openxml php") // Set tags
-> setCategory ("Test result file"); // Set category
// Location aaa * Provide anchor for the following code location
// Add data to the table
$ objPHPExcel-> setActiveSheetIndex (0) // Set the first built-in table (there can be multiple tables in an xls file) as active
-> setCellValue ('A1', 'Hello') // Set data for the cell of the table
-> setCellValue ('B2', 'world!') // Data format can be string
-> setCellValue ('C1', 12) // Digital
-> setCellValue ('D2', 12) //
-> setCellValue ('D3', true) // Boolean
-> setCellValue ('D4', '= SUM (C1: D2)'); // formula
// Get the currently active table, note that $ objActSheet will often be used in the following tutorials
$ objActSheet = $ objPHPExcel-> getActiveSheet ();
// position bbb * provide anchor for code position below
// Set a name for the currently active table
$ objActSheet-> setTitle ('Simple2222');
The code is not over yet, you can copy the code below to decide what we are going to do
What we will do is
1, Generate a file directly
$ objWriter = PHPExcel_IOFactory :: createWriter ($ objPHPExcel, 'Excel2007');
$ objWriter-> save ('myexchel.xlsx');
pdf file
// download a pdf file
header ('Content-Type: application / pdf');
header ('Content-Disposition: attachment; filename = "01simple.pdf"');
header ('Cache-Control: max-age = 0');
$ objWriter = PHPExcel_IOFactory :: createWriter ($ objPHPExcel, 'PDF');
$ objWriter-> save ('php: // output');
exit;
// Generate a pdf file
$ objWriter = PHPExcel_IOFactory :: createWriter ($ objPHPExcel, 'PDF');
$ objWriter-> save ('a.pdf');
CSV file
$ objWriter = PHPExcel_IOFactory :: createWriter ($ objPHPExcel, 'CSV')-> setDelimiter (',') // Set separator
-> setEnclosure ('"') // Set the enclosing character
-> setLineEnding ("\ r \ n") // Set line separator
-> setSheetIndex (0) // Set active sheet
-> save (str_replace ('. php', '.csv', __FILE__));
HTML file
$ objWriter = PHPExcel_IOFactory :: createWriter ($ objPHPExcel, 'HTML'); // Convert $ objPHPEcel object to HTML format
$ objWriter-> setSheetIndex (0); // Set the active sheet
//$objWriter->setImagesRoot('http://www.example.com ');
$ objWriter-> save (str_replace ('. php', '.htm', __FILE__)); // Save the file
Format table and data
Set the default font and text size Anchor: aaa
$ objPHPExcel-> getDefaultStyle ()-> getFont ()-> setName ('Arial');
$ objPHPExcel-> getDefaultStyle ()-> getFont ()-> setSize (20);
Date format Anchor: bbb
// Get second value variable
$ dateTimeNow = time ();
// The three tables are set to the current actual date format, time format, date and time format
// First set the cell value to the Excel format value converted by the PHPExcel_Shared_Date :: PHPToExcel method, and then use it to get the number style in the cell style and then set the display format
$ objActSheet-> setCellValue ('C9', PHPExcel_Shared_Date :: PHPToExcel ($ dateTimeNow));
$ objActSheet-> getStyle ('C9')-> getNumberFormat ()-> setFormatCode (PHPExcel_Style_NumberFormat :: FORMAT_DATE_YYYYMMDD2);
$ objActSheet-> setCellValue ('C10', PHPExcel_Shared_Date :: PHPToExcel ($ dateTimeNow));
$ objActSheet-> getStyle ('C10')-> getNumberFormat ()-> setFormatCode (PHPExcel_Style_NumberFormat :: FORMAT_DATE_TIME4);
$ objActSheet-> setCellValue ('C10', PHPExcel_Shared_Date :: PHPToExcel ($ dateTimeNow));
$ objActSheet-> getStyle ('C10')-> getNumberFormat ()-> setFormatCode (PHPExcel_Style_NumberFormat :: FORMAT_DATE_TIME4);
// Set the number format from E4 to E13 to EUR
$ objPHPExcel-> getActiveSheet ()-> getStyle ('E4: E13')-> getNumberFormat ()-> setFormatCode (PHPExcel_Style_NumberFormat :: FORMAT_CURRENCY_EUR_SIMPLE);
Set header and footer for file printing Anchor: bbb
// Set the header and footer when printing (after setting, you can see the effect through print preview) & * in the string seems to be some variables
$ objActSheet-> getHeaderFooter ()-> setOddHeader ('& L & G & C & H Please treat this document as confidential!');
$ objActSheet-> getHeaderFooter ()-> setOddFooter ('& L & B'. $ objPHPExcel-> getPropert
ies ()-> getTitle (). '& RPage & P of & N');
Set page text orientation and page size Anchor: bbb
$ objPHPExcel-> getActiveSheet ()-> getPageSetup ()-> setOrientation (PHPExcel_Worksheet_PageSetup :: ORIENTATION_LANDSCAPE);
$ objPHPExcel-> getActiveSheet ()-> getPageSetup ()-> setPaperSize (PHPExcel_Worksheet_PageSetup :: PAPERSIZE_A4); // A4 paper size
Add a picture for the header. Valid in office. Invalid in wps. Anchor: bbb
$ objDrawing = new PHPExcel_Worksheet_HeaderFooterDrawing ();
$ objDrawing-> setName ('PHPExcel logo');
$ objDrawing-> setPath ('./ images / phpexcel_logo.gif');
$ objDrawing-> setHeight (36);
$ objPHPExcel-> getActiveSheet ()-> getHeaderFooter ()-> addImage ($ objDrawing, PHPExcel_Worksheet_HeaderFooter :: IMAGE_HEADER_LEFT);
Set cell comment Anchor: bbb
// Add comments to cells
$ objPHPExcel-> getActiveSheet ()-> getComment ('E13')-> setAuthor ('PHPExcel'); // Set author
$ objCommentRichText = $ objPHPExcel-> getActiveSheet ()-> getComment ('E13')-> getText ()-> createTextRun ('PHPExcel:'); // Add annotation
$ objCommentRichText-> getFont ()-> setBold (true); // Bold the existing annotation
$ objPHPExcel-> getActiveSheet ()-> getComment ('E13')-> getText ()-> createTextRun ("\ r \ n"); // Add more comments
$ objPHPExcel-> getActiveSheet ()-> getComment ('E13')-> getText ()-> createTextRun ('Total amount on the current invoice, including VAT.');
$ objPHPExcel-> getActiveSheet ()-> getComment ('E13')-> setWidth ('100pt'); // Set the width and height of the annotation display, valid in office and invalid in wps
$ objPHPExcel-> getActiveSheet ()-> getComment ('E13')-> setHeight ('100pt');
$ objPHPExcel-> getActiveSheet ()-> getComment ('E13')-> setMarginLeft ('150pt');
$ objPHPExcel-> getActiveSheet ()-> getComment ('E13')-> getFillColor ()-> setRGB ('EEEEEE'); // Set the background color, valid in office and invalid in wps
Add text block to see the renderings. Valid in office. Invalid in wps. Anchor: bbb
// Probably translate Create a rich text box Office is valid wps is invalid
$ objRichText = new PHPExcel_RichText ();
$ objRichText-> createText ('This invoice is'); // Write text
// Add text and set this text bold italic and text color
$ objPayable = $ objRichText-> createTextRun ('payable within thirty days after the end of the month');
$ objPayable-> getFont ()-> setBold (true);
$ objPayable-> getFont ()-> setItalic (true);
$ objPayable-> getFont ()-> setColor (new PHPExcel_Style_Color (PHPExcel_Style_Color :: COLOR_DARKGREEN));
$ objRichText-> createText (', unless specified otherwise on the invoice.');
// Write the text in cell A18
$ objPHPExcel-> getActiveSheet ()-> getCell ('A18')-> setValue ($ objRichText);
Merge and split cells Anchor: bbb
$ objPHPExcel-> getActiveSheet ()-> mergeCells ('A28: B28'); // A28: B28 merge
$ objPHPExcel-> getActiveSheet ()-> unmergeCells ('A28: B28'); // A28: B28 and then split
Cell password protection Anchor: bbb
// Cell password protected from modification
$ objPHPExcel-> getActiveSheet ()-> getProtection ()-> setSheet (true); // In order to protect any table, it must be set to true
$ objPHPExcel-> getActiveSheet ()-> protectCells ('A3: E13', 'PHPExcel'); // Protect A3 to E13 The encryption password is PHPExcel
$ objPHPExcel-> getActiveSheet ()-> getStyle ('B1')-> getProtection ()-> setLocked (PHPExcel_Style_Protection :: PROTECTION_UNPROTECTED); // Remove protection
Set the cell font Anchor: bbb
// Set B1's text font to Candara. The bold underline of the 20th has a background color.
$ objPHPExcel-> getActiveSheet ()-> getStyle ('B1')-> getFont ()-> setName ('Candara');
$ objPHPExcel-> getActiveSheet ()-> getStyle ('B1')-> getFont ()-> setSize (20);
$ objPHPExcel-> getActiveSheet ()-> getStyle ('B1')-> getFont ()-> setBold (true);
$ objPHPExcel-> getActiveSheet ()-> getStyle ('B1')-> getFont ()-> setUnderline (PHPExcel_Style_Font :: UNDERLINE_SINGLE);
$ objPHPExcel-> getActiveSheet ()-> getStyle ('B1')-> getFont ()-> getColor ()-> setARGB (PHPExcel_Style_Color :: COLOR_WHITE);
Text alignment anchor: bbb
$ objPHPExcel-> getActiveSheet ()-> getStyle ('D11')-> getAlignment ()-> setHorizontal (PHPExcel_Style_Alignment :: HORIZONTAL_RIGHT); // Align in the horizontal direction
$ objPHPExcel-> getActiveSheet ()-> getStyle ('A18')-> getAlignment ()-> setHorizontal (PHPExcel_Style_Alignment :: HORIZONTAL_JUSTIFY); // Align both ends horizontally
$ objPHPExcel-> getActiveSheet ()-> getStyle ('A18')-> getAlignment ()-> setVertical (PHPExcel_Style_Alignment :: VERTICAL_CENTER); // Center in the vertical direction
Set cell border Anchor: bbb
$ styleThinBlackBorderOutline = array (
'borders' => array (
'outline' => array (
'style' => PHPExcel_Style_Border :: BORDER_THIN, // Set border style
// 'style' => PHPExcel_Style_Border :: BORDER_THICK, another style
'color' => array ('argb' => 'FF000000'), // Set the border color
),
),
);
$ objPHPExcel-> getActiveSheet ()-> getStyle ('A4: E10')-> applyFromArray ($ styleThinBlackBorderOutline);
Background fill color anchor: bbb
// Set the fill style and background color
$ objPHPExcel-> getActiveSheet ()-> getStyle ('A1: E1')-> getFill ()-> setFillType (PHPExcel_Style_Fill :: FILL_SOLID);
$ objPHPExcel-> getActiveSheet ()-> getStyle ('A1: E1')-> getFill ()-> getStartColor ()-> setARGB ('FF808080');
Set url hyperlink to cell content Anchor: bbb
$ objActSheet-> getCell ('E26')-> getHyperlink ()-> setUrl ('http://www.phpexcel.net'); // Hyperlink URL address
$ objActSheet-> getCell ('E26')-> getHyperlink ()-> setTooltip ('Navigate to website'); // mouse up to connect to the prompt information
Add a picture to the table Anchor: bbb
$ objDrawing = new PHPExcel_Worksheet_Drawing ();
$ objDrawing-> setName ('Paid');
$ objDrawing-> setDescription ('Paid');
$ objDrawing-> setPath ('./ images / paid.png'); // Picture introduction position
$ objDrawing-> setCoordinates ('B15'); // Image add position
$ objDrawing-> setOffsetX (210);
$ objDrawing-> setRotation (25);
$ objDrawing-> setHeight (36);
$ objDrawing-> getShadow ()-> setVisible (true);
$ objDrawing-> getShadow ()-> setDirection (45);
$ objDrawing-> setWorksheet ($ objPHPExcel-> getActiveSheet ());
// You can also add pictures produced by the gd library, see the example 25 for details
Create a new worksheet and set the worksheet label color Anchor: bbb
$ objExcel-> createSheet ();
$ objPHPExcel-> setActiveSheetIndex (1); // Set the second table as the active table, providing operation handle
$ objExcel-> getSheet (1)-> setTitle ('Test 2'); // Get the second table directly for setting, rename the worksheet to test 2
$ objPHPExcel-> getActiveSheet ()-> getTabColor ()-> setARGB ('FF0094FF'); // Set the label color
Add or delete rows and columns Anchor: bbb
$ objPHPExcel-> getActiveSheet ()-> insertNewRowBefore (6, 10); // Add 10 lines before line 6
$ objPHPExcel-> getActiveSheet ()-> removeRow (6, 10); // delete 10 lines from line 6
$ objPHPExcel-> getActiveSheet ()-> insertNewColumnBefore ('E', 5); // Add 5 categories from before column E
$ objPHPExcel-> getActiveSheet ()-> removeColumn ('E', 5); // Remove 5 columns from the beginning of column E
Hide and show a column Anchor: bbb
$ objPHPExcel-> getActiveSheet ()-> getColumnDimension ('C')-> setVisible (false); // Hide
$ objPHPExcel-> getActiveSheet ()-> getColumnDimension ('D')-> setVisible (true); // Display
Rename the label name of the active table Anchor: bbb
$ objPHPExcel-> getActiveSheet ()-> setTitle ('Invoice');
Set up worksheet security
$ objPHPExcel-> getActiveSheet ()-> getProtection ()-> setPassword ('PHPExcel');
$ objPHPExcel-> getActiveSheet ()-> getProtection ()-> setSheet (true); // This should be enabled in order to enable any of the following!
$ objPHPExcel-> getActiveSheet ()-> getProtection ()-> setSort (true);
$ objPHPExcel-> getActiveSheet ()-> getProtection ()-> setInsertRows (true);
$ objPHPExcel-> getActiveSheet ()-> getProtection ()-> setFormatCells (true);
Set pagination (mainly used for printing) Anchor: bbb
// Set a cell as the footer
$ objPHPExcel-> getActiveSheet ()-> setBreak ('A'. $ i, PHPExcel_Worksheet :: BREAK_ROW);
Filling a table with an array Anchor: bbb
// The contents of the array are filled from A2
$ dataArray = array (array ("2010", "Q1", "United States", 790),
array ("2010", "Q2", "United States", 730),
);
$ objPHPExcel-> getActiveSheet ()-> fromArray ($ dataArray, NULL, 'A2');
Set up automatic filtering Anchor: bbb
$ objPHPExcel-> getActiveSheet ()-> setAutoFilter ($ objPHPExcel-> getActiveSheet ()-> calculateWorksheetDimension ());
//$objPHPExcel->getActiveSheet()->calculateWorksheetDimension()....get all the contents of line A1
Print out to all formulas
$ objCalc = PHPExcel_Calculation :: getInstance ();
print_r ($ objCalc-> listFunctionNames ())
Set the range of cell values Anchor: bbb
$ objValidation = $ objPHPExcel-> getActiveSheet ()-> getCell ('B3')-> getDataValidation ();
$ objValidation-> setType (PHPExcel_Cell_DataValidation :: TYPE_WHOLE);
$ objValidation-> setErrorStyle (PHPExcel_Cell_DataValidation :: STYLE_STOP);
$ objValidation-> setAllowBlank (true);
$ objValidation-> setShowInputMessage (true); // Set display prompt message
$ objValidation-> setShowErrorMessage (true); // Set display error message
$ objValidation-> setErrorTitle ('Input error'); // error title
// $ objValidation-> setShowDropDown (true);
$ objValidation-> setError ('Only numbers between 10 and 20 are allowed!'); // error content
$ objValidation-> setPromptTitle ('Allowed input'); // Set the prompt title
$ objValidation-> setPrompt ('Only numbers between 10 and 20 are allowed.'); // Prompt content
$ objValidation-> setFormula1 (10); // Set the maximum value
$ objValidation-> setFormula2 (120); // Set the minimum value
// Or set it like this $ objValidation-> setFormula2 (1,5,6,7); The set value is a number from 1,5,6,7
other
$ objPHPExcel-> getActiveSheet ()-> getStyle ('B5')-> getAlignment ()-> setShrinkToFit (true); // Wrap automatically if the length is not enough
$ objPHPExcel-> getActiveSheet ()-> getStyle ('B5')-> getAlignment ()-> setShrinkToFit (true); // Automatically convert the display font size to make the content display
$ objPHPExcel-> getActiveSheet ()-> getCell (B14)-> getValue (); // Get the value, it is possible to get the formula
$ objPHPExcel-> getActiveSheet ()-> getCell (B14)-> getCalculatedValue (); // Get the calculated value
Import or read files
// Load a file by PHPExcel_IOFactory :: load method, load will automatically determine the file suffix name to import the corresponding processing class, read the format contains xlsx / xls / xlsm / ods / slk / csv / xml / gnumeric
require_once '../Classes/PHPExcel/IOFactory.php';
$ objPHPExcel = PHPExcel_IOFactory :: load (
// The default table of loaded files (usually the first one) returns a multi-dimensional array through the toArray method
$ dataArray = $ objPHPExcel-> getActiveSheet ()-> toArray ();
// Write directly to an xlsx file after reading
$ objWriter = PHPExcel_IOFactory :: createWriter ($ objPHPExcel, 'Excel2007'); // $ objPHPExcel is the resource read above
$ objWriter-> save (str_replace ('. php', '.xlsx', __FILE__));
Loop through the data
$ objReader = PHPExcel_IOFactory :: createReader ('Excel2007'); // Create a 2007 read object
$ objPHPExcel = $ objReader-> load ("05featuredemo.xlsx"); // Read an xlsx file
foreach ($ objPHPExcel-> getWorksheetIterator () as $ worksheet) {// traverse the worksheet
echo 'Worksheet-', $ worksheet-> getTitle (), PHP_EOL;
foreach ($ worksheet-> getRowIterator () as $ row) {// Traverse rows
echo 'Row number-', $ row-> getRowIndex (), PHP_EOL;
$ cellIterator = $ row-> getCellIterator (); // Get all columns
$ cellIterator-> setIterateOnlyExistingCells (false); // Loop all cells, even if it is not set
foreach ($ cellIterator as $ cell) {// traverse the column
if (! is_null ($ cell)) {// If the column is not empty, get its coordinates and calculated value
echo 'Cell-', $ cell-> getCoordinate (), '-', $ cell-> getCalculatedValue (), PHP_EOL;
}
}
}
}
Array inserted into table
// Insert data 3 rows of data
$ data = array (array ('title' => 'Excel for dummies',
'price' => 17.99,
'quantity' => 2
),
array ('title' => 'PHP for dummies',
'price' => 15.99,
'quantity' => 1
),
array ('title' => 'Inside OOP',
'price' => 12.95,
'quantity' => 1
)
);
$ baseRow = 5; // Specify to insert after line 5
foreach ($ data as $ r => $ dataRow) {
$ row = $ baseRow + $ r; // $ row is the row number of the loop operation row
$ objPHPExcel-> getActiveSheet ()-> insertNewRowBefore ($ row, 1); // Add an empty line before the operation line number, and the line number of this empty line becomes the current line number
// The corresponding lines are attached with data and number
$ objPHPExcel-> getActiveSheet ()-> setCellValue ('A'. $ row, $ r + 1);
$ objPHPExcel-> getActiveSheet ()-> setCellValue ('B'. $ row, $ dataRow ['title']);
$ objPHPExcel-> getActiveSheet ()-> setCellValue ('C'. $ row, $ dataRow ['price']);
$ objPHPExcel-> getActiveSheet ()-> setCellValue ('D'. $ row, $ dataRow ['quantity']);
$ objPHPExcel-> getActiveSheet ()-> setCellValue ('E'. $ row, '= C'. $ row. '* D'. $ row);
}
$ objPHPExcel-> getActiveSheet ()-> removeRow ($ baseRow-1,1); // Finally delete the fourth line, which is required for the example, here is a delete example for everyone
Author: Huang Cong
Source: http://www.cnblogs.com/huangcong/
The copyright of this article belongs to the author and the blog garden. Reprinting is welcome, but this paragraph statement must be retained without the author's consent, and a link to the original text should be given in the obvious position of the article page, otherwise the right to pursue legal responsibility is reserved.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.