-2

I am populating many tables which has vehicle mileage details on a monthly basis of a particular year. I have managed to popuate the table and output the results on the webpage, but I am stuck on how to take the exact tables displayed on the HTML webpage to a spreadsheet, for the excel generation I am using the PHPSpreadsheet library.

The HTML tables with data populated from the database is as below, One Of Many Tables

Tables With Null Data

This table which is shown in the HTML page is just for my development purposes but the actual requirements is to generate the excel sheet report. How can i achieve this by generating the report into one single phpspreadsheet at once.

The code for fetching data from database and outputting into the tables is as follows,

<?php
if (isset($_POST['btnreport'])) {
$querymain = "SELECT * FROM users";
$resultsmain = mysqli_query($connect,$querymain);
if ($resultsmain->num_rows>0) {
    while ($userid = mysqli_fetch_assoc($resultsmain)) {
        $approvedkm = $userid['approved_kmpl'];
        ?>
        <table class="table" class="mt-3 mb-3">
        <thead class="bg-dark text-light">
        <tr>
        <th colspan="3"><?php echo $userid['company']; ?></th>
        <th colspan="3"><?php echo $userid['name']; ?></th>
        <th colspan="3"><?php echo $userid['approved_kmpl'];?> KM</th>
        </tr>
        </thead>
        <thead>
        <tr>
        <th>Month</th>
        <th>Daily Mileage</th>
        <th>Usage For Month</th>
        <th>Required Per Month</th>
        <th>Excess Used</th>
        <th>(%)</th>
        <th>KM/L</th>
        <th>Consumed Liters</th>
        <th>Cost</th>
        </tr>
        </thead>
        
        <tbody>
        <?php  
        $varglobal1;
        //Closing Mileage For Month Query
        $closingmileage = "SELECT extract(MONTH from date) as Month,
        MAX(mileage) as CloseMile FROM mileagesnew 
        WHERE user_id='".$userid['id']."' 
        AND extract(YEAR FROM date) ='2020' 
        group by Month 
        ORDER BY month desc";
        
        //Usage For Month Query
        $usageformonth = "SELECT extract(MONTH from date) as Month, MIN(mileage) as StartMile FROM 
mileagesnew WHERE user_id='".$userid['id']."' AND extract(YEAR FROM date) ='2020' group by Month 
ORDER BY Month desc";
        
        //Working Days Fetch From Table Calender
        $workingdays = "SELECT Month, Working_Days as Work FROM calender WHERE Year ='2020' group by 
Month ORDER BY Month desc";
        
        //Query To Get The Sum Of Liters Pumped Per Month
        $fuelpumped = "SELECT extract(MONTH from date) as Month, SUM(`fuel`) FROM mileagesnew WHERE 
user_id='".$userid['id']."' AND extract(YEAR FROM date) ='2020' group by Month ORDER BY Month desc";
        
        //Final Query For Calculating Fuel Cost Per Month
        $fueltotalcost = "SELECT extract(MONTH from date) as Month, SUM(`fuel_cost`) FROM mileagesnew 
WHERE user_id='".$userid['id']."' AND extract(YEAR FROM date) ='2020' group by Month ORDER BY Month 
desc";
        
        $closingres = mysqli_query($connect,$closingmileage);
        $usage = mysqli_query($connect,$usageformonth);
        $working = mysqli_query($connect,$workingdays);
        $fuelpumpedresul = mysqli_query($connect,$fuelpumped);
        $finalfuelcstres = mysqli_query($connect,$fueltotalcost);
        
        if ($closingres->num_rows>0) {        
            while ($closingrow = mysqli_fetch_assoc($closingres) AND $usagerow= 
 mysqli_fetch_assoc($usage) AND $workrow = mysqli_fetch_assoc($working) AND $fuelpumpedresrow = 
 mysqli_fetch_assoc($fuelpumpedresul) AND $flcostrow = mysqli_fetch_assoc($finalfuelcstres)) {
                
                $firstrange = $closingrow['CloseMile'];
                $lastrange = $usagerow['StartMile'];
                $usageformonthres = $firstrange - $lastrange;
                
                $reqformont = $workrow['Work'];
                $reqformonth = $approvedkm * $reqformont;
                $excessusedcal = $usageformonthres - $reqformonth;
                ?>
                <tr>
                <td><?php echo $closingrow['Month']; ?></td>
                
                <td><?php echo $closingrow['CloseMile']; ?></td>
                <td><?php echo $usageformonthres; ?></td>
                <td><?php echo $reqformonth; ?></td>
                <td><?php echo $excessusedcal; ?></td>
                <td><?php echo ($excessusedcal - $usageformonthres)/100;?>%</td>
                <td>
                <?php
                error_reporting(0);
                $kmplfinal = $usageformonthres / floatval($fuelpumpedresrow['SUM(`fuel`)']);
                if (floatval($fuelpumpedresrow['SUM(`fuel`)']) == 0) {;
                    print_r(0);
                }
                else {
                    echo round($kmplfinal,4);
                }
                ?>
                </td>
                <td><?php echo round($fuelpumpedresrow['SUM(`fuel`)'],2);?></td>
                <td><?php echo round($flcostrow['SUM(`fuel_cost`)'],2);?></td>
                </tr>
                <?php
                
            }
        } else{
            echo "No Data Found";
        }
        ?>
        
        </tbody>
        <thead class="bg-dark text-light">
        <tr>
        <th colspan="2">Total</th>
        <th>Sum Of Above</th>
        <th>Sum Of Above</th>
        <th>Excess Usage Sum</th>
        <th></th>
        <th></th>
        <th>Consumed L's Sum</th>
        <th>Total Cost</th>
        </tr>
        </thead>
        </table>
        <br>
        <br>
        <br>
        <?php
    }
}
}
?>
Developer
  • 145
  • 2
  • 5
  • 20
  • don't post images from data and so on see https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question – nbk May 31 '21 at 17:48
  • Did you try https://github.com/elidickinson/php-export-data ??? – Indra Kumar S May 31 '21 at 17:50
  • @nbk How do you expect me to paste the table into here instead of the image, I have added the code as well in the text format in the original question. – Developer Jun 01 '21 at 06:02
  • @IndraKumarS I already have PHPSpreadheet, is there a way to do this with PHPSpreadsheet instead of some other library? – Developer Jun 01 '21 at 06:03
  • @Developer Export the data and tables reduce the existing data t a minimum and replace all personal data, make a https://dbfiddle.uk, and also show the result you want. – nbk Jun 01 '21 at 08:19
  • @Developer i couldnt see any code that uses PhpSpreadSheet ? – Indra Kumar S Jun 01 '21 at 11:23
  • @IndraKumarS I dont have PHPSpreadsheet code for this but i have used that excel libary in other parts of the system where only an individual users details were required. In that case i can access the cell elements and loop via the list since its just one user. But in this case all the data displayed on the table is required and the records you see are of all users not indivudual user records. – Developer Jun 01 '21 at 16:38
  • @IndraKumarS I tried the PHPSpreadsheet code for this part of the system as well but it didnt work, so I removed it and moved on to try finding a better solution – Developer Jun 01 '21 at 16:40
  • @Developer i can help you with this library. https://github.com/elidickinson/php-export-data its very simple – Indra Kumar S Jun 02 '21 at 03:01

1 Answers1

0

You can do it through this library easily.

Download this class and save it as php-export-data.class.php in same folder where you have this exporting script.

The following script will directly download the file.

<?php

// When executed in a browser, this script will prompt for download 
// of 'test.xls' which can then be opened by Excel or OpenOffice.

require 'php-export-data.class.php';

// 'browser' tells the library to stream the data directly to the browser.
// other options are 'file' or 'string'
// 'test.xls' is the filename that the browser will use when attempting to 
// save the download
$exporter = new ExportDataExcel('browser', 'test.xls');

$exporter->initialize(); // starts streaming data to web browser


$month = 'Month';
$mileage = 'Daily Mileage';
$usage = 'Usage For Month';
$required = 'Required Per Month';
$excess = 'Excess Used';
$percentage = '(%)';
$kmpl = 'KM/L';
$consumed = 'Consumed Liters';
$cost = 'Cost';

// Creating Heaer Row
$row = array( 
        $month,
        $mileage,
        $usage,
        $required,
        $excess,
        $percentage,
        $kmpl,
        $consumed,
        $cost
);

$exporter->addRow($row); 

// Inside your while loop ()
 
while(.....) {
     .......
     .......
    // Build a row from variables
    $row = array( 
        $month,
        $mileage,
        $usage,
        $required,
        $excess,
        $percentage,
        $kmpl,
        $consumed,
        $cost
    );
    $exporter->addRow($row); 
}



// pass addRow() an array and it converts it to Excel XML format and sends 
// it to the browser
$exporter->addRow($row); 
 

$exporter->finalize(); // writes the footer, flushes remaining data to browser.

exit(); // all done

?>
Indra Kumar S
  • 2,818
  • 2
  • 16
  • 27