How to create formated Excel lists from mySQL database? - php

I use a mySQL database and have to create some lists in Excel format (xlsx). The Excel sheets must be formated. For csv export I use phpExcel (I know, it is obsolete but still working).
Which add on do I need to create formated Excel sheets from my mySQL database. I use php to create the frontend.
Thanks,
Markus

This is just a copy of the function i use. It just launches the function when a specific $_GET isset. The function creates a xlsx file. If you want to export the file as .csv you can just change the file extension and edit text/xlsm to text/csv
$gg = $db->prepare("SELECT * FROM beta_mails ORDER BY created DESC");
$gg->execute();
$ggg = $gg->get_result();
$gg->store_result();
while ($row = $ggg->fetch_assoc()) {
$data[] = $row;
}
function getprelaunchCSV(){
global $data;
header('Content-Type: text/xlsx; charset=utf-8');
header('Content-Disposition: attachment; filename=data.xlsx');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('ID', 'EMAIL', 'OPRETTET'));
foreach ($data as $rowCSV){
fputcsv($output, [$rowCSV["id"], decrypt($rowCSV["email"]), $rowCSV["created"]]);
}
fclose($output);
die();
}
if (isset($_GET["getlist"]) && $_GET["getlist"] == "1") {
echo getprelaunchcsv();
header("Location:admin?success=1");
}

Related

Export data into CSV file in Symfony

I have console app made in Symfony3, where user can import CSV file (which is validate) into database. I need to put records which haven't passed validation into separate file.
I use LeagueCSV to read CSV file and I try to use it to write unvalidated records but it doesn't work.
This is my code:
$reader = Reader::createFromPath($input->getArgument('lokalizacja'));
$reader->setDelimiter(';');
$reader->setHeaderOffset(0);
$results = $reader->getRecords();
foreach ($results as $row) {
$year = $row['description'];
$isValid = false;
if ($row['qty'] > 0 && $row['price'] > 0 && !empty($row['mpn'])) {
$isValid = true;
$rok = filter_var($row['description'], FILTER_SANITIZE_NUMBER_INT);
$product = (new Produkt())
->setMpn($row['mpn'])
->setQty($row['qty'])
->setYear($year)
->setPrice($row['price']);
$this->em->persist($product); }
if ($row['qty'] == 0 || $row['price'] == 0 || empty($row['mpn'])) {
$writer = Writer::createFromPath('/path/to/saved/file.csv', 'w+');
$writer->insertOne([$row['mpn'], $row['qty'], $row['price'],
$row['description']]);
continue;
}
}
$this->em->flush();
All records which passed validation are successfully saved in the database but I have problem with others records. In new CSV file I have only first, one record which haven't passed validation and nothing more. What am I doing wrong? I tried with
$writer->insertAll($results); //using an array
Or with if...else statment but that's nothing.
Also I made ...else statement where unvalidated records are saved in other table in database and its works but I don't know how to immediately convert them into CSV file.
Don't know symfony but CSV output is pretty simple. FWIW...
Pass this an array, like a fetchall resultset.
<?php
public function outputCSV($data, $useKeysForHeaderRow = true) {
if ($useKeysForHeaderRow) {
array_unshift($data, array_keys(reset($data)));
}
$outputBuffer = fopen("php://output", 'w');
foreach($data as $v) {
fputcsv($outputBuffer, $v);
}
fclose($outputBuffer);
}
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="FooBarFileName_' . date('Ymd') . '.csv"');
header("Pragma: no-cache");
header("Expires: 0");
$this->outputCSV($results);
If you look at the doc page for the writer you will see a warning at the top which states
When inserting records into a CSV document using League\Csv\Writer, first insert all the data that need to be inserted before starting manipulating the CSV. If you manipulate your CSV document before insertion, you may change the file cursor position and erase your data.
Your code calls
$writer = Writer::createFromPath('/path/to/saved/file.csv', 'w+');
$writer->insertOne([$row['mpn'], $row['qty'], $row['price'], $row['description']]);
In every iteration the condition is met, this appears to be overwriting or dropping your previous insert every time. You should declare the $writer once before the loop starts in order to preserve each insert.
$writer = Writer::createFromPath('/path/to/saved/file.csv', 'w+');
foreach ($results as $row) {
// do stuff with $writer
}

Export HTML table to CSV file

I am making a script which gets a table from your mail and puts it into a CSV file.
This is the code I use to transfer my html table to CSV
$html = str_get_html($outputstr);
// For Excel
header('Content-type: application/ms-excel');
// Download File
header('Content-Disposition: attachment; filename=sample.csv');
$fp = fopen("php://output", "w");
// Take out empty lines
foreach($html->find('tr') as $element) {
$td = array();
foreach( $element->find('th') as $row) {
$td [] = $row->plaintext;
}
foreach( $element->find('td') as $row) {
$td [] = $row->plaintext;
}
fputcsv($fp, $td);
}
fclose($fp);
The only problem that I'm getting is that when I am opening the CSV file, some of the empty columns have a strange character:
I cannot read through with my PHP script to export it to a database
fgetcsv($handle, 1000, "\t");
How can I fix this problem?
Do I fix this by modifying the code on the part where I create the CSV file or where I read the CSV file when I'm transferring it to a MySQL database?
When I use an online html to CSV converter it works fine and I am not facing this issue then.
If there is any code needed then I'd love to share it.
Any help would be appreciated.
Have you tried setting your charset to UTF-8? Additionally, you're not setting this up as a CSV with your header, instead it is an Excel file.
header("content-type:application/csv;charset=UTF-8");

Output to CSV generating errors

I don't have a lot of experience with using the fputcsv function.
I'm trying to make a function, by which an admin can download a file with all the user information.
The CSV should be generated in this way :
Serial Number Username Email etc etc
And then the records from a query.
I have this function which I'm using to generate the csv file :
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
// open raw memory as file so no temp files needed, you might run out of memory though
$f = fopen('php://memory', 'w');
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
// rewrind the "file" with the csv lines
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachement; filename="'.$filename.'";');
// make php send the generated csv lines to the browser
fpassthru($f);
}
And then I call the function:
<?php
include 'inc/inc.functions.php';
include 'dbconnector.php';
$query="SELECT * from users order by email LIMIT 0,30";
$result=mysql_query($query,$db) or die(mysql_error($db));
$array=mysql_fetch_array($result);
foreach($array as $arr)
{
array_to_csv_download($arr,"records.csv",":");
}
?>
The CSV generated displays: Warning, Invalid argument supplied for foreach.
What should I do to display in the way I require?
UPDATE
http://i.imgur.com/2xH0gT1.png
You're currently calling your function for a single row in the database, rather than for the entire result set. The following should use your function correctly:
$query = "SELECT * from users order by email LIMIT 0,30";
$result = mysql_query($query,$db) or die(mysql_error($db));
$array = array();
# Headers
$array[] = array("Serial Number","Username","Email","etc etc");
while($row = mysql_fetch_row($result)) {
$array[] = $row;
}
array_to_csv_download($array,"records.csv",":");

Exporting SQLite table to Excel using PHP script

I am working on a project and new to PHP and I need to know how to export the table data from SQLite to Excel.
I am able to do it from database but I do not know how to export to Excel using PHP.
<?php
$db = new sqlite3('I:\Preeti\explor\WebMobility.db');
$results = $db->query('SELECT * FROM VerbaliData');
while ($row = $results->fetchArray()) {
var_dump($row);
}
?>
The easiest method whould be to write your results into a CSV file which opens in Excel in a readable format.
See here for more information: http://php.net/fputcsv
$fp = fopen('file.csv', 'w');
while ($row = $results->fetchArray()) {
fputcsv($fp, $row);
}
fclose($fp);

Issue creating CSV in PHP MySQL

I have to run a pairing algorithm for a game and when the pairing is done, I display the pairing on HTML and create a csv file as well. Right now, once I am done with pairing, I create a multidimensional array to store the specific value and then pass it to the function in same php file to generate the csv file. However, doing this outputs the entire page code i.e. html and php code to the .csv file. Here is the code:
function performPairing()
{
....
$count=0;
$resultArray[][] = array();
while ($currrow = #mysql_fetch_row($result))
{
$playerone = $currrow;
$playertwo = #mysql_fetch_row($result);
$resultArray[$count][] = $playerone[1];
$resultArray[$count][] = $playerone[0];
$resultArray[$count][] = $playertwo[1];
$resultArray[$count][] = $playertwo[0];
$count++;
updateforeachrow($playerone, $playertwo);
}
generateDocument($resultArray, $count);
}
function generateDocument($resultArray, $count)
{
$output = fopen('php://temp/maxmemory'.(5*1024*1024), 'r+');
$columns = array('Player One Col1', 'Player One Col2', 'Player Two Col1', 'Player Two Col2');
fputcsv($output, $columns);
for ($index=0 ; $index <=$count; $index++)
{
fputcsv($output, $resultArray[$index]);
}
rewind($output);
$export = stream_get_contents($output);
fclose($output);
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename = "export.csv"');
echo $export;
}
However doing this outputs the entire html code to csv rather than specific rows. Can anyone please help me on this?
. make string
. output string to file
. send header with (is this allowed this way?)
use file_put_contents ( filename, str ), and than send it with headers.
Make code simpler :)

Categories