PHP - Phpspreadsheet Create A New Worksheet On Salesperson Name Change
I am creating a spreadsheet with phpspreadsheet using sql data. After the first loop that gets all the data I want to loop through the data again and create new worksheets for each salesperson(ARJSALESEMPLOYEEID). This code gets me all the data in a worksheet how would I then run through it again and create the worksheets "createSheets($row[ARJSALESEMPLOYEEID])" for each salesperson?
<?php //call the autoload require 'vendor/autoload.php'; //load phpspreadsheet class using namespaces use PhpOffice\PhpSpreadsheet\Spreadsheet; //call iofactory instead of xlsx writer use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Fill; //styling arrays //table head style $tableHead = [ 'font'=>[ 'color'=>[ 'rgb'=>'FFFFFF' ], 'bold'=>true, 'size'=>11 ], 'fill'=>[ 'fillType' => Fill::FILL_SOLID, 'startColor' => [ 'rgb' => '538ED5' ] ] ]; //even row $evenRow = [ 'fill'=>[ 'fillType' => Fill::FILL_SOLID, 'startColor' => [ 'rgb' => 'F2F2F2' ] ] ]; //odd row $oddRow = [ 'fill'=>[ 'fillType' => Fill::FILL_SOLID, 'startColor' => [ 'rgb' => 'FFFFFF' ] ] ]; //styling arrays end $exrow=3; //make a new spreadsheet object $spreadsheet = new Spreadsheet(); //get current active sheet (first sheet) $sheet = $spreadsheet->getActiveSheet(); //set default font $spreadsheet->getDefaultStyle() ->getFont() ->setName('Arial') ->setSize(10); //heading $spreadsheet->getActiveSheet() ->setCellValue('A1',"Comission"); //merge heading $spreadsheet->getActiveSheet()->mergeCells("A1:P1"); // set font style $spreadsheet->getActiveSheet()->getStyle('A1')->getFont()->setSize(20); // set cell alignment $spreadsheet->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER); //setting column width $spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(25); $spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(20); $spreadsheet->getActiveSheet()->getColumnDimension('C')->setWidth(20); $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(30); $spreadsheet->getActiveSheet()->getColumnDimension('E')->setWidth(25); $spreadsheet->getActiveSheet()->getColumnDimension('F')->setWidth(25); $spreadsheet->getActiveSheet()->getColumnDimension('G')->setWidth(25); $spreadsheet->getActiveSheet()->getColumnDimension('H')->setWidth(10); $spreadsheet->getActiveSheet()->getColumnDimension('I')->setWidth(10); $spreadsheet->getActiveSheet()->getColumnDimension('J')->setWidth(10); $spreadsheet->getActiveSheet()->getColumnDimension('K')->setWidth(10); $spreadsheet->getActiveSheet()->getColumnDimension('L')->setWidth(10); $spreadsheet->getActiveSheet()->getColumnDimension('M')->setWidth(10); $spreadsheet->getActiveSheet()->getColumnDimension('N')->setWidth(10); $spreadsheet->getActiveSheet()->getColumnDimension('O')->setWidth(10); $spreadsheet->getActiveSheet()->getColumnDimension('P')->setWidth(10); //header text//current row $spreadsheet->getActiveSheet() ->setCellValue('A2',"INVOICE DATE") ->setCellValue('B2',"SALESPERSON") ->setCellValue('C2',"INVOICE ID") ->setCellValue('D2',"ORDER ID") ->setCellValue('E2',"ORDER DATE") ->setCellValue('F2',"CUSTOMER ID") ->setCellValue('G2',"NAME") ->setCellValue('H2',"GROUP ID") ->setCellValue('I2',"STATE") ->setCellValue('J2',"QTY") ->setCellValue('K2',"PART") ->setCellValue('L2',"UOM") ->setCellValue('M2',"GROUP") ->setCellValue('N2',"GROSS") ->setCellValue('O2',"DISCOUNT") ->setCellValue('P2',"NET"); //set font style and background color $spreadsheet->getActiveSheet()->getStyle('A2:P2')->applyFromArray($tableHead); // the connection $connect =odbc_connect(removed); if(!$connect) { exit("Connection Failed: " . $connect); } //the sql query $sql="SELECT ARPINVOICEDATE ,ARJSALESEMPLOYEEID ,ARPARINVOICEID ,UARPSALESORDERNUMBER ,ompCreatedDate ,ARPCUSTOMERORGANIZATIONID ,CMONAME ,CMOCUSTOMERGROUPID ,cmoState ,ARLINVOICEQUANTITY ,ARLPARTID ,ARLUNITOFMEASURE ,ARLPARTGROUPID ,ARLFULLEXTENDEDPRICEBASE ,ARLEXTENDEDDISCOUNTBASE ,ARLEXTENDEDPRICEBASE ,ARLSALESORDERID ,case when arlPartGroupID = 'PROMO' then 4.00 when arlPartGroupID = 'DC' then 2.00 when cmocustomergroupid = 'LIST' then 5.00 when cmocustomergroupid = 'VOL' then 4.00 when cmocustomergroupid = 'VOL2' then 4.00 when cmocustomergroupid = 'VOL2' then 5.00 else 5.00 end as comission_percent FROM M1_KF.dbo.ARInvoices INNER JOIN M1_KF.dbo.ARInvoiceLines ON arpARInvoiceID = arlARInvoiceID LEFT OUTER JOIN M1_KF.dbo.organizations ON ARPCUSTOMERORGANIZATIONID = cmoorganizationid LEFT OUTER JOIN M1_KF.dbo.arinvoicesalespeople ON arparinvoiceid = arjarinvoiceid left outer join M1_KF.dbo.SalesOrders on ompSalesOrderID=UARPSALESORDERNUMBER where arlsalesorderid !='' and arpPostedDate >='05-01-2019'and arpPostedDate <'06-01-2019' and arlPartGroupID not in('FRT') ORDER BY ARJSALESEMPLOYEEID,arpARInvoiceID"; //run the query $result =odbc_exec($connect,$sql); if(!$result){ exit("Error in SQL"); } while ($row = odbc_fetch_array($result)) { //loop through the data $spreadsheet->getActiveSheet() ->setCellValue('A'.$exrow ,$row['ARPINVOICEDATE']) ->setCellValue('B'.$exrow ,$row['ARJSALESEMPLOYEEID']) ->setCellValue('C'.$exrow ,$row['ARPARINVOICEID']) ->setCellValue('D'.$exrow ,$row['UARPSALESORDERNUMBER']) ->setCellValue('E'.$exrow ,$row['ompCreatedDate']) ->setCellValue('F'.$exrow ,$row['ARPCUSTOMERORGANIZATIONID']) ->setCellValue('G'.$exrow ,$row['CMONAME']) ->setCellValue('H'.$exrow ,$row['CMOCUSTOMERGROUPID']) ->setCellValue('I'.$exrow ,$row['cmoState']) ->setCellValue('J'.$exrow ,$row['ARLINVOICEQUANTITY']) ->setCellValue('K'.$exrow ,$row['ARLPARTID']) ->setCellValue('L'.$exrow ,$row['ARLUNITOFMEASURE']) ->setCellValue('M'.$exrow ,$row['ARLPARTGROUPID']) ->setCellValue('N'.$exrow ,$row['ARLFULLEXTENDEDPRICEBASE']) ->setCellValue('O'.$exrow ,$row['ARLEXTENDEDDISCOUNTBASE']) ->setCellValue('P'.$exrow ,$row['ARLEXTENDEDPRICEBASE']); //set row style if( $exrow % 2 == 0 ){ //even row $spreadsheet->getActiveSheet()->getStyle('A'.$exrow.':P'.$exrow)->applyFromArray($evenRow); }else{ //odd row $spreadsheet->getActiveSheet()->getStyle('A'.$exrow.':P'.$exrow)->applyFromArray($oddRow); } //increment row $exrow++; } //define first row and last row $firstRow=2; $lastRow=$exrow-1; //set the autofilter $spreadsheet->getActiveSheet()->setAutoFilter("A".$firstRow.":P".$lastRow); odbc_close($connect); //set the header first, so the result will be treated as an xlsx file. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); //make it an attachment so we can define filename header('Content-Disposition: attachment;filename="result.xlsx"'); //create IOFactory object $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); //save into php output $writer->save('php://output');
Similar TutorialsI'm trying to dynamically group a range of rows using PHPSpreadsheet and having a lot of trouble thinking through the logic. My code so far looks like this: $worksheet = $spreadsheet->getActiveSheet(); // Get the highest row number and column letter referenced in the worksheet $highestRow = $worksheet->getHighestRow(); // e.g. 10 $highestColumn = $worksheet->getHighestColumn(); // e.g 'F' // Increment the highest column letter $highestColumn++; $job_num_chk = ''; $grp_start_row = ''; //format the inserted records for ($row = 2; $row <= $highestRow; ++$row) { //$spreadsheet->getActiveSheet()->getRowDimension($row)->setRowHeight(53); for ($col = 'A'; $col != $highestColumn; ++$col) { $spreadsheet->getActiveSheet()->getStyle($col . $row)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP); $spreadsheet->getActiveSheet()->getStyle($col . $row)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT); if ($col == 'B') { $cur_job_num = $spreadsheet->getActiveSheet()->getCell($col . $row)->getValue(); //get current job number //check if job number is different if ( $job_num_chk !== $cur_job_num ) { $spreadsheet->getActiveSheet()->insertNewRowBefore($row, 1); //insert dividing row //set dividing row to black $spreadsheet->getActiveSheet()->getStyle('A'.$row.':N'.$row)->getFill() ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID) ->getStartColor()->setARGB('000000'); $job_num_chk = $cur_job_num; //update job number } } } } This line: $grp_start_row = ''; Is where I'm hitting a mental wall...here's what the spreadsheet looks like so far:
I want to be able to group the rows 101-105 in that example like below:
I need to be able to determine where the start row is and the end row is in order to use the grouping feature (https://phpspreadsheet.readthedocs.io/en/latest/topics/recipes/#groupoutline-a-row) Thanks everyone. Hello everyone, I am working on a form that is similar to a shopping cart system and I am thinking of creating a button that submits the checked value and saves them to a $_SESSION variable. And also a link that links to a cart.html that takes the values of a $_SESSION variable. I am have trouble figuring what tag/attribute should I use in order to achieve that.
Right now my code attached below submits the checked values to cart.html directly. However I want my submit button to save the checked box to a $_SESSION variable and STAY on the same page. And then I will implement a <a> to link to the cart.php.
I researched a little bit about this subject and I know it's somewhat related to ajax/jquery. I just wanted to know more about it from you guys. I appreciate your attention for reading the post and Thanks!
Below is the form that I currently have:
<form name= "finalForm" method="POST" action="cart.php"> <input type="Submit" name="finalSelected"/> <?php foreach($FinalName as $key => $item) {?> <tr> <td><input type="checkbox" name="fSelected[]" value="<?php echo htmlspecialchars($FinalID[$key])?>" /> <?php echo "$FinalID[$key] & $item";?> </td> </tr> <?php } ;?>Below is the code for cart.php <?php require ('connect_db.php'); if(isset($_POST['finalSelected'])) { if(!empty($_POST['fSelected'])) { $chosen = $_POST['fSelected']; foreach ($chosen as $item) echo "aID selected: $item </br>"; $delimit = implode(", ", $chosen); print_r($delimit); } } if(isset($delimit)) { $cartSQL = "SELECT * from article where aID in ($delimit)"; $cartQuery = mysqli_query($dbc, $cartSQL) or die (mysqli_error($dbc)); while($row = mysqli_fetch_array($cartQuery, MYSQLI_BOTH)) { $aTitle[] = $row[ 'name' ]; } } ?> <table> <?php if(isset($delimit)) { $c=0; foreach($aTitle as $item) {?> <tr> <td> <?php echo $aTitle[$c]; $c++;?> </td> </tr> <?php }}?> </table> HOw to create this header?
I give +. thx
http://i.snag.gy/15Ep4.jpg
hi, I'm currently trying to resize and create pictures and .jpg/jpeg & .gif works perfectly but .png just creates an empty 0bit image, why?! Code: [Select] $ = imagecreatefrompng(); imagecopyresampled(); imagepng(); I'm doing something like that and it - as said - works great with .jpg and gif but at png it just fucks up. :/ Hii i want to create an api of the short url site ( http://torrentz.0fees.net ). In the api page it is says that Code: [Select] API Our API allows you to provide short url functionality to any of your existing websites. Url Only To generate a url via the API, send a POST or GET request to the site in the following format: - http://torrentz.0fees.net/index.php?api=1&return_url_text=1&longUrl={URL} This site will then generate the short url and return it as plain text. i.e: - http://torrentz.0fees.net/a1 I have created an form but not able to use it. The form script is shown below. Code: [Select] <form name="input" action="html_form_action.asp" method="get"> Username: <input type="text" name="user" /> <input type="submit" value="Submit" /> </form> Whenever i'm putting the ( http://torrentz.0fees.net/index.php?api=1&return_url_text=1&longUrl={URL} ) it shows an error. I know that the input url must be used in the ( {URL} ) section but how can i do that using php Can anyone help me with code... HI all, I am building a php application and i am wanting to use notifications. At the moment i am just wanting to understand the methodology behind this. I dont necessarily have a use case for these notifications yet but i am going to base it off of the following: A user submits something to the database, another user gets a notifications that this has happened. I see the notifications being something appearing in the header bar (saying "you have a notification"...) I know that i will need to use ajax for this and JS/JQ but i am not really sure where to start with this. I have done some research and have come up a little blank. My main question at the moment is how does the submission of data to the database trigger the notification? As always and help here is appreciated. Kind Regards Adam I'm using a php $_POST variable as the name of a file that I want to create. fopen() , according to my understanding open the file if it exists or creates it if it doesn't. $Ref = $_POST['Ref']; I using each reference element of $Ref as the name of a file in a certain directory. So if $Ref[$i] exists as a file name in a certain directory, append to the file, if it doesn't create the file in that directory and write to it. Do I use the file path of the file within fopen()? fopen(./References/$Ref,a) or fopen(./References/$Ref,w)? I am trying create my xml file in this format: Code: [Select] <?xml version="1.0" encoding="UTF-8" ?> - <playlist id="Adobe"> <vid desc="5 minute cardio warm-up" contenu="side jumps, arm curls ..." src="videos/set2_first_5min.flv" thumb="thumbs/set2_first.png" /> <vid desc="5 minutes of no rest workout moves" contenu="Football drills, front kicks ..." src="videos/set2_second_5min.flv" thumb="thumbs/set2_second.png" /> <vid desc="last 5 minutes of Set 1" contenu="MC Hammer ..." src="videos/set2_third_5min.flv" thumb="thumbs/set2_third.png" /> <vid desc="5 minute cardio warm-up" contenu="jumping jacks, presses and squats" src="videos/Set1_first.flv" thumb="thumbs/set1_first.jpg" /> <vid desc="5 minutes of no rest workout moves" contenu="shin kicks ..." src="videos/Set1_mid.flv" thumb="thumbs/set1_mid.jpg" /> <vid desc="last 5 minutes of Set 1" contenu="MC Hammer ..." src="videos/Set1_last.flv" thumb="thumbs/set1_last.jpg" /> </playlist>[/color] I'm not having trouble getting and looping through the data from mySQL. I'm getting confused with what's a child element, attribute node, and attribute value. Can someone who has worked with the DOMDocument steer me in the right direction? sample code is the best request Thanks! When creating a PHP document we use echo ''; to wrap HTML into PHP, so why does it seem to me that people always say to create a form using PHP you must break it up by using HTML to show the form itself? Is there a way to create the form, and do all that is required using PHP and wrapping PHP around HTML to make it work? I can't imagine its impossible. Please i have questions on how to create a file system server. were you clients could upload files and download their files in the future. Is this professional to store the files in database Hello all That forum is my last desperate attemp to do what i want to do. Ok here is the story I want to create a simple rss feed in conjuction with php and mysql. I dont want admin areas ect , i just want when i insert a new listing to my database to be able shown up to my (future) rss subscribers. To be more technically specific i want to show to my surfers updates about 2 tables in my database not all the tables. The example i found so far were about only 1 table, plus i was encounting errors to my script. I would like some ideas, directions if someone is kind enough to help a sad developer Thanks in advance! Hi, How could I make a php script that creates a new folder (with the name as the date) every day automatically? Cheers, George I have a table in my database for users. On the registration page I want to create another table with the id of the user as the table name. $sql = "CREATE TABLE IF NOT EXISTS `id_prod` ( ) how do i modify this line so that it takes the id from the user table and creates a new table with id as name followed by prod. Hi, Here is simple question. I have this array: array([0]=>name [1]=>Tony); How can i change into array(name=>Tony); ? Thank you, ayok For the life of me I can not figure out why this is not creating the table in the database. Second set of eyes would be great.
function install_kudos() { global $wpdb; $table_name = $wpdb->prefix . 'acikudosnew'; if ($wpdb->get_var('SHOW TABLES LIKE ' .$table_name) != $table_name) { $sql = "CREATE TABLE $table_name ( kudoid int(9) NOT NULL AUTO_INCREMENT, kudomsg text NOT NULL, kudoagent text NON NULL, kudocust text NOT NULL, kudoacct int(16) NOT NULL, kudoclient varchar(100) NOT NULL, kudoloc text NOT NULL, kudoentry TIMESTAMP DEFAULT CURRENT_TIMESTAMP, kudoadmin text NOT NULL, kudopic varchar(55) DEFAULT '' NOT NULL, PRIMARY KEY (kudoid) )"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } } register_activation_hook(__FILE__, 'install_kudos');
I have a simple form and I run my script without any errors. I click my btn and I would like to see my echo errors but no errors show up when I have no value in textboxes. I have tried if(isset($_Post["submit"])) and if($_SERVER["REQUEST_METHOD"] == "post") What I think is nether of there ifs are becoming valid on my btn click. <?php $nameerror = $twoerror = $errormsg = ""; // PHP Procedural MYSQLi // connect to mysql database with phpmyadmin $servername = "localhost"; $username = "root"; $password = "password"; $dbname = "test"; $connection = new mysqli($servername, $username, $password, $dbname); //if(isset($_Post["submit"])) if($_SERVER["REQUEST_METHOD"] == "post") { if(empty(trim($_Post["name"]))) { $nameerror = "Name is required"; } else { $namesafe = mysqli_real_escape_string($connection, $_Post["name"]); } if(empty(trim($_Post["two"]))) { $twoerror = "Two is required"; } else { $twosafe = mysqli_real_escape_string($connection, $_Post["two"]); } if($namesafe != "" && $twosafe != "") { $sqlInsert = "INSERT INTO tester(name, two) " . "VALUES('". $namesafe ."','". $twosafe ."')"; if(mysqli_query($connection, $sqlInsert)) { echo "Successfully entered."; } else { echo "NOT successful error: " . $sqlInsert . "<br>" . mysqli_error($connection); } } } mysqli_close($connection); ?> <?php if(!$connection) { die("Connection Failed! " . mysqli_connect_error()); } echo "Connected Successfully@!"; ?> <section class="text-align" id="section-content"> <div id="alertMessages" class="container rounded"></div> <div id="contentdiv" class="container rounded"> <form id="formtest" class="rounded" method="post" > <!-- action="" --> <h3>PHP Create</h3> <?php if(isset($errormsg)) { // echo "<div><span>"; echo $errormsg; // echo "</span></div>"; } ?> <div> <div class="form-group"> <input type="text" class="form-control" id="txtName" name="name" /> <label for="txtName">Name </label> <?php if(isset($nameerror)) { echo '<span class="error">' . $nameerror . '</span>'; } ?> <!-- ? php//if(isset($_Post["name"])) echo htmlspecialchars($_Post["name"]); ? >" /> ---> <!-- <span class="error"><?php //echo $nameerror; ?></span> --> </div> <div> <input type="text" class="form-control" id="txttwo" name="two" /> <label for="txttwo">Text Two </label> <?php if(isset($twoerror)) { echo '<span class="error">' . $twoerror . '</span>'; } ?> </div> </div> <button type="submit" class="btn btn-lg btn-primary btn-block" name="submit">Click</button> </form> </div> </section>
Hey Everyone, I need to have the ability to create PDF/X1A documents. My initial thoughts are it would be easy as i have created PDFs in the past with no hassle. I have been trawling the google and various blogs but with no joy. Does anyone have any experience creating PDF/X1A documents in PHP ? Is it possible ? Regards, -Ben Hello, I am creating zip file of multiple files using PHP and downloading it. Problem is that: zip file is getting extracted by only WinRAR, its not getti ng extracted by default windows extracter or other software. Here is code which I have written -
$file_folder = 'referral-resume/'; Hi all I'm trying to create an XML file to be used within Excel. The data is drawn dynamically from my database depending on the information supplied by the user. However when I run it, I get a complain from Excel about some missing whitespace. any ideas? Code: [Select] <?php $output='<?xml version="1.0"?> <?mso-application progid="Excel.Sheet"?> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40"> <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"> <Author>Europcar</Author> <LastAuthor>Europcar</LastAuthor> <Created>2011-10-28T10:48:37Z</Created> <Company>Europcar</Company> <Version>11.9999</Version> </DocumentProperties> <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"> <WindowHeight>11760</WindowHeight> <WindowWidth>15195</WindowWidth> <WindowTopX>480</WindowTopX> <WindowTopY>75</WindowTopY> <ProtectStructure>False</ProtectStructure> <ProtectWindows>False</ProtectWindows> </ExcelWorkbook> <Styles> <Style ss:ID="Default" ss:Name="Normal"> <Alignment ss:Vertical="Bottom"/> <Borders/> <Font/> <Interior/> <NumberFormat/> <Protection/> </Style> </Styles> <Worksheet ss:Name="Sheet1"> <Table ss:ExpandedColumnCount="'.$columns.'" ss:ExpandedRowCount="'.($count+5).'" x:FullColumns="1"x:FullRows="1">'; //$output.='<Column ss:AutoFitWidth="0" ss:Width="50"/>/n'; $output.='<Row>'; foreach ($titles as $value){ if(is_numeric(substr($value,0,1))){ $value=substr($value,1); } $output.='<Cell><Data ss:Type="String">'.$value.'</Data></Cell>'."LF"; } /*$output.='</Row>'; foreach ($dataOut as $value){ $output.='<Row>'; foreach($value as $values){ if(strlen($values)<1){ $values=" "; } $output.= '<Cell><Data ss:Type="String">'.$values.'</Data></Cell>'; } $output.='</Row>'; }*/ $output.=' </Table> <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"> <Selected/> <Panes> <Pane> <Number>3</Number> <ActiveRow>'.($count+5).'</ActiveRow> <ActiveCol>'.$columns.'</ActiveCol> </Pane> </Panes> <ProtectObjects>False</ProtectObjects> <ProtectScenarios>False</ProtectScenarios> </WorksheetOptions> </Worksheet> </Workbook>'; |