I am currently developing an App for my school to record Class Cleanliness Results for each class, so I need to convert the results collated in MySQL table into Microsoft Excel using PHP, preferably also able to be opened by a Android OS Phone.
I used the following PHP code:
<?PHP
$mysqli_user = "(user)";
$mysqli_password = "(password)";
$mysqli_host = "(host)";
$mysqli_database = "(database)";
$filename = "grading_results_" . time() . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$link = mysqli_connect($mysqli_host,$mysqli_user,$mysqli_password,$mysqli_database);
$query = 'SELECT * FROM (table_name)';
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)){
print implode("\t", $row) . "\n";
}
mysqli_close($link);
?>
This is how my table looks like in phpMyAdmin:
https://www.dropbox.com/s/7pr3gh06zta5d8u/Snip20150618_2.png?dl=0
This is how the Excel file looks like after I used this code to convert.
https://www.dropbox.com/s/571m9lfj64tklpc/Snip20150618_3.png?dl=0
Why is there no columns and rows? I need the Excel file to be exactly the same formatting and style as the table in phpMyAdmin. Can anyone help edit my code instead of providing me a brand new code?
Thanks in advance for your answers!
Manual
Run tour localhost and log in to phpMyAdmin
Click on your database then click on the table which you want to get
Excel.
then
then press GO button
With Code
define ("DB_HOST", "localhost");
define ("DB_USER", "root");
define ("DB_PASS","");
define ("DB_NAME","DATABASE_NAME");
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
then
$setCounter = 0;
$setExcelName = "download_excal_file";
$setSql = "YOUR SQL QUERY GOES HERE";
$setRec = mysql_query($setSql);
$setCounter = mysql_num_fields($setRec);
for ($i = 0; $i < $setCounter; $i++) {
$setMainHeader .= mysql_field_name($setRec, $i)."\t";
}
while($rec = mysql_fetch_row($setRec)) {
$rowLine = '';
foreach($rec as $value) {
if(!isset($value) || $value == "") {
$value = "\t";
} else {
//It escape all the special charactor, quotes from the data.
$value = strip_tags(str_replace('"', '""', $value));
$value = '"' . $value . '"' . "\t";
}
$rowLine .= $value;
}
$setData .= trim($rowLine)."\n";
}
$setData = str_replace("\r", "", $setData);
if ($setData == "") {
$setData = "no matching records found";
}
$setCounter = mysql_num_fields($setRec);
//This Header is used to make data download instead of display the data
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$setExcelName."_Report.xls");
header("Pragma: no-cache");
header("Expires: 0");
//It will print all the Table row as Excel file row with selected column name as header.
echo ucwords($setMainHeader)."\n".$setData."\n";
More About Code
SELECT id, name, email INTO OUTFILE '/tmp/ram.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY ‘\\’
LINES TERMINATED BY '\n'
FROM users WHERE id=1
Here /tmp/ is address where u want to store the csv
<?php
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
// print your data here. note the following:
// - cells/columns are separated by tabs ("\t")
// - rows are separated by newlines ("\n")
// for example:
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
?>
// You can fetch the data from the database and display in the table. Then put the table in echo to get Excel file.
Related
I've used phpspreadsheet to export data to excel.
This works fine but, sometime it gives the error as invalid numeric value for data type numeric in c:\xamp\htdocs\phpspreadsheet\vendor\phpoffice\spreadsheet\src\phpspeeadsheet\Cell\Cell.php:221
The image that I've attached is the error I get. Please help me.
session_start();
//php_spreadsheet_export.php
include 'C:/xampp/htdocs/phpspreadsheet/vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
$connect = new PDO("mysql:host=localhost;dbname=IDC", "root", " ");
$school=$_SESSION['code'];
$name="name";
$query = "SELECT * FROM SCHOOL WHERE School='".$school."' AND Name!='".$name."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
if(isset($_POST["export"]))
{
$file = new Spreadsheet();
$active_sheet = $file->getActiveSheet();
$active_sheet->setCellValue('A1', 'Name');
$active_sheet->setCellValue('B1', 'Phone');
$active_sheet->setCellValue('C1', 'DOB');
$active_sheet->setCellValue('D1', 'Father');
$active_sheet->setCellValue('E1', 'Mother');
$active_sheet->setCellValue('F1', 'Address');
$active_sheet->setCellValue('G1', 'Blood');
$active_sheet->setCellValue('H1', 'Admission');
$active_sheet->setCellValue('I1', 'Photo link');
$active_sheet->setCellValue('J1', 'Class');
$active_sheet->setCellValue('K1', 'Section');
$count = 2;
foreach($result as $row)
{
$active_sheet->setCellValue('A' . $count, $row["Name"]);
$active_sheet->setCellValue('B' . $count, $row["Phone"]);
$active_sheet->setCellValue('C' . $count, $row["DOB"]);
$active_sheet->setCellValue('D' . $count, $row["Father"]);
$active_sheet->setCellValue('E' . $count, $row["Mother"]);
$active_sheet->setCellValue('F' . $count, $row["Address"]);
$active_sheet->setCellValue('G' . $count, $row["Blood"]);
$active_sheet->setCellValue('H' . $count, $row["Adm_no"]);
$active_sheet->setCellValue('I' . $count, $row["Photo_link"]);
$active_sheet->setCellValue('J' . $count, $row["Class"]);
$active_sheet->setCellValue('K' . $count, $row["Section"]);
$count = $count + 1;
}
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($file, $_POST["file_type"]);
$file_name = time() . '.' . strtolower($_POST["file_type"]);
$writer->save($file_name);
header('Content-Type: application/x-www-form-urlencoded');
header('Content-Transfer-Encoding: Binary');
header("Content-disposition: attachment; filename=\"".$file_name."\"");
readfile($file_name);
unlink($file_name);
exit;
}
?> ```
This is the code and it works fine for all data except for this error.
I got the error solved. The error was that, the numbers had a space at the end and was not matching the data type detected by value binder. So I set the data type as string.
Here is the changed code, if it will help anyone who is facing similar trouble.
$active-sheet->setCellValueExplicit( 'B'. $count, $row["phone"],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
I got this answer from
https://phpspreadsheet.readthedocs.io/en/latest/topics/accessing-cells/
Hi I want to save the file in excel format in my local folder. For this I am creating an api which will be scheduled to call at every night and save the data in file every night.
My attempt is :
class SaveExcel
{
function SaveExcel()
{
}
function saveData()
{
$file_result = "";
$database = new Database(Constants::DBHOST, Constants::DBUSER, Constants::DBPASS, Constants::DBNAME);
$dbConnection = $database->getDB();
date_default_timezone_set('Asia/Kolkata');
$date = date('m/d/Y h:i:s a', time());
$DB_TBLName = "location"; //MySQL Table Name
$filename = "LocationHistory(" . $date . ")"; //File Name
//create MySQL connection
$stmt = $dbConnection->prepare("Select * from $DB_TBLName");
$stmt->execute();
$columnHeader = '';
$columnHeader = "loc_id" . "\t" . "user_id" . "\t" . "address" . "\t" . "date_time" . "\t";
$setData = '';
while ($rec = $stmt->FETCH(PDO::FETCH_ASSOC)) {
$rowData = '';
foreach ($rec as $value) {
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
// file_put_contents('history/' . $filename, $setData);
return ucwords($columnHeader)."\n".$setData."\n";
}
}
?>
By this I am getting the output as :
"Loc_id\tUser_id\tAddress\tDate_time\t\n\"118\"\t\"1\"\t\"19.166488899999997\"\t\"72.8510805\"\t\"16, Aarey Rd, Jay Prakash Nagar, Goregaon East, Mumbai, Maharashtra 400063, India\"\t\"2018-03-03 18:05:45\"\n\"119\"\t\"1\"\t\"19.165215999999997\"\t\"72.8509167\"\t\"MU Chambers, Jay Prakash Nagar, Goregaon West, Mumbai, Maharashtra 400063, India\"\t\"2018-03-03 18:22:14\"\n\"120\"\t\"1\"\t\"19.1651942\"\t\"72.85087469999999\"
now I want to save this data in excel format in local folder.
How can I do this?
Please help.. Thank you.
EDIT :
This code is working well.. Now I just want to give the path to the file. Now its getting saved under the project directory I want to get it saved in another directory. How Can I?
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowCount = 1;
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, 'Employee');
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, 'Address');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, 'Date Time');
$rowCount++;
while($row = $stmt->FETCH(PDO::FETCH_ASSOC)){
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $user_name);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['address']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $row['date_time']);
$rowCount++;
}
$current_date = preg_replace('/\s+/', '', $date);
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$name = '/path/to/folder/xyz.xlsx';
$objWriter->save($user_name.$current_date.'.xlsx');
return 'File Saved';
What you are showing here is a TSV (tab-separated values) string, which is readable by Excel, but it's not a full Excel spreadsheet (e.g. you can't have colors etc.). This is good enough for many applications, and it can also be read by any app that reads TSVs (from Notepad++ to LibreOffice), which is an advantage.
However, if you want to create actual Excel files, it's much more difficult. There are libraries out there that do it, like this open-source one: https://github.com/PHPOffice/PhpSpreadsheet
you need to add header of type excel on your code.
$filename = date('m/d/Y h:i:s a', time());
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
application/xls work on < excel 2007. so if get error on excel, you can change that to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
in other way, PHPExcel is a good plugin to customize your output excel
hope this help you.
This code I am using to download result from sql server query in excel .
Connection & query works fine and I have already installed sqlsrv extensions properly.
But still I am getting error like these
"Use of undefined constant SQLSRV_FETCH_ASSOC - assumed
SQLSRV_FETCH_ASSOC'"
"Warning: sqlsrv_fetch_array() expects parameter 2 to be long"
I think the problem is with SQLSRV_FETCH_ASSOC.
Any help would be appreciated.
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
$serverName = "********";
$connectionInfo = array( "Database"=>"****", "UID"=>"***", "PWD"=>"*****");
$connect = sqlsrv_connect( $serverName, $connectionInfo);
// filename for download
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
$query="select * from business_partners ORDER BY 1 desc";
$result = sqlsrv_query($connect, $query) or die('A error occured: ' . sqlsrv_errors());
while(false !== ($row = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC)))
{
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}**strong text**
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit;
I have no explanation why the constant wouldn't be defined while the extension is clearly loaded, but you should be able to circumvent the problem by defining it yourself.
SQLSRV_FETCH_ASSOC has the value 2, so you should just add this somewhere, at best in a file you include always:
if ( !defined( 'SQLSRV_FETCH_ASSOC' ) )
define( 'SQLSRV_FETCH_ASSOC', 2 );
The if ( !defined() ) clause makes sure that your code doesn't break later, when the actual problem is fixed and the constant suddenly reappears.
Alternatively, if you only use it once in the file and it isn't really worth defining the constant (except for readability) you can just use the actual value as a parameter:
$row = sqlsrv_fetch_array( $result, 2 ); // 2 = SQLSRV_FETCH_ASSOC
my code works successfully . but i dont know how to save the .csv file to a seperate directory D:\xampp\htdocs\works_try\export_files. and my file resides in D:\xampp\htdocs\works_try\master\file.php my code given below .
<?php
$server='localhost';
$login='root';
$password='';
$db='tc';
$filename='export1.csv';
$conn=mysqli_connect($server, $login, $password,$db);
$fp = fopen('export_files/../'.$filename, "w");
$sql="SELECT * FROM student";
$res = mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($res);
$line = "";
$comma = "";
foreach($row as $name => $value) {
$line .= $comma . '"' . str_replace('"', '""', $name) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
mysqli_data_seek($res, 0);
while($row = mysqli_fetch_assoc($res)) {
$line = "";
$comma = "";
foreach($row as $value) {
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
}
fclose($fp);
echo " success :) !!!!!!!!!!!!!!!!!!!!!! Please check the file ";
?>
i should save the .csv file in folder_name export_files and my php code runs in the folder_name master.my problem is csv file getting saved in folder_name master itself.where file should save in export_files.
if you use fopen($filename, "w") then file will be save inside the folder. if you want to save the file present outside folder ie(export_files is separate folder and file present in seperate folder ) then try this
fopen('../export_files/'.$filename, "w");
the file will be saved inside export_files folder
If you want it in the root folder of the site use this:
$filename='export1.csv';
$conn=mysqli_connect($server, $login, $password,$db);
$fp = fopen('./'.$filename, "w");
you can also use the following code then the path will be in relation to the directory of the running script. e.g. as example going one directory up and in export_files.
$filename = dirname(__FILE__) .'/../export_files/export1.csv';
you can also use other constants like __DIR__ see http://php.net/manual/de/language.constants.predefined.php
I am trying to add data into excel file which is extracted from wordpress database, Actually I am trying to export data (tags) from database into excel file. And I write down a code, but when I click on generate button. This generates empty file.
Please guys check what I am doing wrong.
Codes are below:
if (check_admin_referer('tag-export'))
{
$blogname = str_replace(" ", "", get_option('blogname'));
$date = date("m-d-Y");
$xls_file_name = $blogname."-exported-tags-".$date;
$tags = get_terms( 'post_tag' , 'hide_empty=0' );
$count = count($tags);
if ( $count > 0 )
{
echo 'name' . "\t" . 'slug' . "\n";
foreach ( $tags as $tag )
{
echo $tag->name . "\t" . $tag->slug . "\n";
}
}
ob_clean();
echo $xls_file;
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=$xls_file_name.xls" );
exit();
}
The above codes are not writing data into excel file. please check and let me know.
Just based on your existing code:
if (check_admin_referer('tag-export'))
{
$blogname = str_replace(" ", "", get_option('blogname'));
$date = date("m-d-Y");
$xls_file_name = $blogname."-exported-tags-".$date;
$tags = get_terms( 'post_tag' , 'hide_empty=0' );
$count = count($tags);
$xls_file = '';
if ( $count > 0 )
{
$xls_file .= 'name' . "\t" . 'slug' . "\n";
foreach ( $tags as $tag )
{
$xls_file .= $tag->name . "\t" . $tag->slug . "\n";
}
}
ob_clean();
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=$xls_file_name.xls" );
echo $xls_file;
exit();
}
A more general suggestion, not a solution for your coding problem: create an HTML table file from the code and then open it in Excel for conversion. Doing it so you'll have a better understand on what's going on with your code: you can add var_dumps or simply debug it like a normal web page.
Having an html table is also useful because excel works quite well in converting it to XLS files.
After your HTML file works well, then you can apply necessary formatting/header to the code in order to create the xls file from scratch.