I am trying to export record from db to excel using PHP (Codeignitor) and then Import the same excel file again using PHP (Codignitor)
Export Code IS:
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename=' . date('d-m-Y') . '.xls');
$export .= '<table border="1">';
$export .= '<tr>';
$export .= '<td>Gate Name</td>';
$export .= '<td>ID</td>';
$export .= '<td>Name</td>';
$export .= '<td>Rank</td>';
$export .= '<td>Time</td>';
$export .= '<td>Entry Type</td>';
$export .= '<td>Work Place</td>';
$export .= '<td>Car Type</td>';
$export .= '<td>Car Number</td>';
$export .= '<td>Inspector Name</td>';
$export .= '</tr>';
foreach ($result as $row) {
$export .= '<tr>';
$export .= '<td>' . $row->gate_name . '</td>';
$export .= '<td>' . $row->soldier_id . '</td>';
$export .= '<td>' . $row->soldier_name . '</td>';
$export .= '<td>' . $row->soldier_rank . '</td>';
$export .= '<td>' . $row->time . '</td>';
$export .= '<td>' . $row->entry_type . '</td>';
$export .= '<td>' . $row->work_place . '</td>';
$export .= '<td>' . $row->vehicle_type . '</td>';
$export .= '<td>' . $row->vehicle_number . '</td>';
$export .= '<td>' . $row->inspector_name . '</td>';
$export .= '</tr>';
}
$export .= '</table>';
echo $export;
When I try to emport the downloaded file using This PHP Library - SimpleXLSX.
$SimpleXLSX = new SimpleXLSX($filename);
$data = $SimpleXLSX->rows();
the $data is empty
this library work if I create an excel file by self using MS Excel.
if I try to get file content by using
print_r(file_get_contents($filename));
It return the content with HTML code
Like
<table border="1">
<tr>
<td>Gate Name</td>
<td>ID</td>
<td>Name</td>
<td>Rank</td>
<td>Time</td>
<td>Entry Type</td>
<td>Work Place</td>
<td>Car Type</td>
<td>Car Number</td>
<td>Inspector Name</td>
</tr>
<tr>
<td>Gate 2</td>
<td>1111</td>
<td>فارس الغامدي</td>
<td>ملازم اول</td>
<td>28/02/1435 07:01:00</td>
<td>دخول</td>
<td>قطاع رفحاء</td>
<td>جيب</td>
<td>Tuy 124</td>
<td>عبدالله</td>
</tr>
</table>
I think the problem is with header() function or encoding when Creating Excel file.
Please help me.
Thanks.
SimpleXLSX will read XLSX files and print HTML code, but you cannot convert HTML code to XLSX format using SimpleXLSX. Here's an example of how to do it in PHPExcel:
<?php
$date = date("m-d-Y-g-i-s");
// Include and instantiate PHPExcel object.
include '../lib/PHPExcel/PHPExcel.php';
include '../lib/PHPExcel/PHPExcel/Writer/Excel2007.php';
$objPHPExcel = new PHPExcel();
// Set metadata.
$objPHPExcel->getProperties()->setTitle("Price List $date");
$objPHPExcel->getProperties()->setSubject("$date Price List");
$objPHPExcel->getProperties()->setDescription("The active price list for $date.");
// Set active sheet index at zero.
$objPHPExcel->setActiveSheetIndex(0);
// Determine limit and offset.
if($_GET['limit'] > 0 && $_GET['offset'] > 0) {
$limit = $_GET['limit'];
$offset = $_GET['offset'];
} else {
$limit = 10000;
$offset = 0;
}
// Query the database.
$query = mysql_query("SELECT * FROM `items` LIMIT $offset, $limit") or die(mysql_error());
$c = 0; // Initialize index at zero.
// Set column dimensions.
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
// Loop through data and insert it into their respective columns.
while($row = mysql_fetch_array($query)) {
$c++;
$objPHPExcel->getActiveSheet()->getCell("A$c")->setValueExplicit(stripslashes($row[strStock]), PHPExcel_Cell_DataType::TYPE_STRING);
$objPHPExcel->getActiveSheet()->SetCellValue("B$c", stripslashes(html_entity_decode($row[strDescription])));
$objPHPExcel->getActiveSheet()->SetCellValue("C$c", stripslashes($row[curPrice]));
}
$objPHPExcel->setActiveSheetIndex(0);
// Send headers to download XLSX file.
header('Content-Type: application/vnd.ms-excel');
if(isset($_GET[part]) && isset($_GET[of])) {
header('Content-Disposition: attachment;filename="Price List (Part '.$_GET[part].' of '.$_GET[of].') '.$date.'.xlsx"');
}
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');exit;
?>
Edit: Sorry, this is the code for PHPExcel, not SimpleXLSX. Here is the documentation for PHPExcel.
Related
Exporting MySQL Data to Excel File using the below code:
$i = 0;
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
$rowData = '';
foreach ($row as $value) {
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
$i++;
}
$filename = $i." numbers ".date('d m Y') . ".xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
It successfully exports the file and also opens correctly but there is a dialogue box before it file is opened.
When I use the extension as xlsx, the file is not opening and gives a dialogue box:
Why it is coming and how to remove it?
You have the wrong delimiters for a row use \r\n instead
$i = 0;
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
$rowData = '';
foreach ($row as $value) {
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\r\n";
$i++;
}
If you want you can try
implode("\t", array_values($row)) . "\r\n";
to get your complete rowData to add to setData, php ha sa lot of functions to explore
like implode and array_value.
anther think is , that you should add a header line before using the result of your select.
<?php
require_once("db_connect.php");
$arr = $_GET['arr'];
$selected_header = implode(', ', (array)$arr);
$sql = "SELECT $selected_header FROM release_ ORDER BY id DESC";
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename=CNC-'.date('Ymd').'.xls');
header('Pragma: no-cache');
header('Expires: 0');
$output = '';
$output .= '<table><tr>';
$header_arr = explode(',', $arr);
$len = count($header_arr);
for($a=0; $a<$len; $a++){
$output .= "<th style='width: 100px; text-align: center;'>" . $header_arr[$a] . "</th>";
}
$output .= '</tr>';
$res = mysqli_query($conn, $sql);
/*====this ruins everything=====*/
while($row = $res->fetch_assoc()){
$output = '<tr align="center">';
for($a=0; $a<$len; $a++){
$output .= "<td>" . $header_arr[$a] . "</td>";
}
echo "</tr>\t\n";
}
/*===============================*/
$output .= '</table>';
echo $output;
?>
I am able to get and display the header in the excel file but the content is not displaying at all. I get the whole string of row tag displayed. How am I able to display the data from the database to excel file. Please help.
I have done in my project(Cakephp) you can use like this own way :-
public function ExportToExcel(){
$users_id = $this->Session->read('selected_user_id');
$this->loadModel('User');
$conditions= array('User.usertype !='=>1);
if(!empty($users_id)){
$ids=explode(",",$users_id);
$conditions = array(
'User.id'=>$ids
);
}
$users = $this->User->find('all',array(
'conditions'=>$conditions,
'order'=>array('User.id Desc')
)
);
ini_set('max_execution_time', 600); //increase max_execution_time to 10 min if data set is very large
$filename = "Users" . date("Y.m.d") . ".xls";
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename="' . $filename . '"');
$i = 1;
$row="";
$row_header="S.No."."\t"."Name "."\t"."Email"."\t"."Mobile"."\t"."Address"."\t"."Status"."\n";
if(!empty($users)){
foreach($users as $user){
if($user['User']['status']==1){
$status = "Active";
}
else{
$status = "Inactive";
}
$row .= $i++."\t".$user['User']['firstname'].' '.$user['User']['lastname']
."\t".$user['User']['email']
."\t".$user['User']['phone_number']
."\t".$user['User']['address']
."\t".$status
."\n";
}
}
$this->Session->delete('selected_user_id');
echo($row_header);
echo($row);
die;
}
I'm trying to connect four tables. order_history, orders_list, infistall_order, and delivery_orders. When I run the code into the table of order_history, the results are as what I am expecting. But when I run the code into the webpages, it only selects the value from the table of order_history.
Note: What I mean with running the code into the table of order_history is when I enter phpMyAdmin and go to the order_history table and run SQL there with the SQL code I have.
<?php
include ("config.php");
$results = $mysqli->query
("
SELECT orders_history.transaction_id,
orders_history.items,
orders_history.quantity,
orders_history.one_product_price,
orders_list.status,
orders_list.invoices,
orders_list.payment_method,
orders_list.order_method,
infistall_order.address,
delivery_orders.address,
delivery_orders.service,
delivery_orders.cost,
delivery_orders.city
FROM orders_history
LEFT JOIN orders_list
ON orders_history.transaction_id = orders_list.transaction_id
LEFT JOIN infistall_order
ON orders_history.transaction_id = infistall_order.transaction_id
LEFT JOIN delivery_orders
ON orders_history.transaction_id = delivery_orders.transaction_id
WHERE orders_list.customer_name = 'Klaudia'"
);
Actually I am trying to collect information from all column in all table based on the transaction_id.
$orders = array();
$html = '';
if ($results) {
while($obj = $results->fetch_object()) {
$orders[$obj->transaction_id][$obj->items] = array('quantity' => $obj->quantity, 'invoices' => $obj->one_product_price);
}
$html .= '<table width="70%"><tr>';
$html .= '<td>items</td>';
$html .= '<td>quantity</td>';
$html .= '<td>one_product_price</td>';
$html .= '<td>status</td>';
$html .= '<td>invoices</td>';
$html .= '<td>payment_method</td>';
$html .= '<td>order_method</td>';
$html .= '<td>address</td>';
$html .= '<td>service</td>';
$html .= '<td>cost</td>';
$html .= '<td>city</td></tr>';
foreach ($orders AS $order_id => $order) {
$html .= '<tbody><tr><td rowspan="' . count($order) . '">' . $order_id . '</td>';
$row = 1;
foreach ($order AS $item => $data) {
if ($row > 1) { $html .= '</tr><tr>'; }
$html .= '<td>' . $item . '</td>';
$html .= '<td>' . $data['items'] . '</td>';
$html .= '<td>' . $data['quantity'] . '</td>';
$html .= '<td>' . $data['one_product_price'] . '</td>';
$html .= '<td>' . $data['status'] . '</td>';
$html .= '<td>' . $data['invoices'] . '</td>';
$html .= '<td>' . $data['payment_method'] . '</td>';
$html .= '<td>' . $data['order_method'] . '</td>';
$html .= '<td>' . $data['address'] . '</td>';
$html .= '<td>' . $data['service'] . '</td>';
$html .= '<td>' . $data['cost'] . '</td>';
$html .= '<td>' . $data['city'] . '</td>';
$row++;
}
$html .= '</tr><tbody>';
}
$html .= '</table>';
}
echo $html;
?>
On your loop:
while($obj = $results->fetch_object()) {
$orders[$obj->transaction_id][$obj->items] = array(
'quantity' => $obj->quantity,
'invoices' => $obj->one_product_price
);
}
You can change it to:
while($obj = $results->fetch_object()) {
$orders[$obj->transaction_id][$obj->items][] = array(
'quantity' => $obj->quantity,
'invoices' => $obj->one_product_price
);
}
It will prevent the data from replacing one to another, the [] sign on array is make the array to become dynamic, the key will be count from 0 and will be increment by 1 as you add more data into that array.
I have a web page where i am able to export a .csv file that is readable on excel. The invoice pulls the data from my database to calculate the total and grand total using the following columns:
quantity, packing_price, courier_price
I have noticed that my code doesn't output the correct answer when the prices contains a '£' sound in front of it. Is there a way that i could make this work for both number and currency data types?
CODE:
$output2= "";
$sql2 = mysql_query("
SELECT j.date
, j.order_ref
, j.quantity
, j.packing_price
, j.dispatch_type
, j.courier_price
FROM Jobs j
WHERE j.order_type = 'Retail International'
AND j.confirmed = 'Yes';
");
$columns_total2 = mysql_num_fields($sql2);
$total3 = "Total";
for ($i = 0; $i < $columns_total2; $i++)
{
$heading2 = mysql_field_name($sql2, $i);
$output2 .= '"'.$heading2.'",';
}
$output2 .= $total3;
$output2 .="\n";
$sum2 = 0;
while ($row = mysql_fetch_array($sql2)) {
for ($i = 0; $i < $columns_total2; $i++) {
$output2 .='"'.$row["$i"].'",';
}
$qty2 = $row['quantity'];
$pack_price2 = $row['packing_price'];
$dispatch2 = $row['courier_price'];
$total2 = (($qty2*$pack_price2) + $dispatch2);
$total3 = $total2*1.2;
$output2 .= $total3;
$sum2 += $total3; // Add to overall total
$output2 .="\n";
}
Output:
http://i754.photobucket.com/albums/xx182/rache_R/Screenshot2014-07-03at113133_zpsbcc09900.png
Use this Code....
$output= "<table border='1' width='60%'><tr>";
$sql = " SELECT j.date ,
j.order_ref ,
j.quantity ,
j.packing_price ,
j.dispatch_type ,
j.courier_price
FROM Jobs j
WHERE j.order_type = 'Retail International'
AND j.confirmed = 'Yes' ";
$query = mysql_query($sql);
$total_columns = mysql_num_fields($query);
for ($i = 0; $i < $total_columns; $i++){
$heading = mysql_field_name($query, $i);
$output .= '<td>' . $heading . '</td>';
if(($i+1) == $total_columns) $output .= '<td>Total</td></tr>';
}
while ($row = mysql_fetch_array($query)) {
$total_price = 0;
$total_price =( ( $row['quantity'] * $row['packing_price'] ) +
$row['courier_price'] );
$total_price = $total_price * 1.2;
$timestamp = DateTime::createFromFormat('Y-m-d h:i:s',
$row['date'])->getTimestamp();
$output .= '<tr>';
$output .= '<td>' . date("d/m/Y", $timestamp) . '</td>';
$output .= '<tr>';
$output .= '<td>' . date("d/m/Y", strtotime($row['date']) . '</td>';
$output .= '<td>' . $row['order_ref'] . '</td>';
$output .= '<td>' . $row['quantity']. '</td>';
$output .= '<td>' . $row['packing_price'] . '</td>';
$output .= '<td>' . $row['dispatch_type'] . '</td>';
$output .= '<td>' . $row['courier_price'] . '</td>';
$output .= '<td>' . number_format($total_price, 2) . '</td>';
$output .= '</tr>';
}
$output .= "</table>";
echo '<br>' . $output;
I wonder how can i find out last in table with PHP, aka if that is last then i want to apply different style and content to it.
This is part of my code generating table content.
$content .= '</tr>';
$totalcols = count ($columns);
if (is_array ($tabledata))
{
foreach ($tabledata as $tablevalues)
{
if ($tablevalues[0] == 'dividingline')
{
$content .= '<tr><td colspan="' . $totalcols . '" style="background-color:#efefef;"><div align="left"><b>' . $tablevalues[1] . '</b></div></td></tr>';
continue;
}
else
{
$content .= '<tr>';
foreach ($tablevalues as $tablevalue)
{
$content .= '<td>' . $tablevalue . '</td>';
}
$content .= '</tr>';
continue;
}
}
}
else
{
$content .= '<tr><td align="center" style="border-bottom: none;" colspan="' . $totalcols . '">No Records Found</td></tr>';
}
I know there is option to do something like that with jQuery later on, but I don't want to complicate it and just solve it with php at time when i generate table.
Keep a count:
$count = 1;
foreach ($tablevalues as $tablevalue)
{
$count++;
if( $count > count( $tablevalues)) {
echo "Last td tag is up next! ";
}
$content .= '<td>' . $tablevalue . '</td>';
}
you can execute any code in last loop:
for($i=0;$i<count($tablevalues);$i++)
{
$tablevalue=$tablevalues[$i];
$content .= '<td>' . $tablevalue . '</td>';
if($i==count($tablevalues)-1){
// last loop execution
}
}
here is a somehow trick
foreach ($tablevalues as $k => $tablevalue)
{
if ($k==count($tablevalues)-1)
{
// last td of current row
$content .= '<td>' . $tablevalue . '</td>';
}
else
{
$content .= '<td>' . $tablevalue . '</td>';
}
}
I just hope that your keys of your $tablevalues set match this code.
You should use a for($i = 0; i < count($tablevalues); $i++) {} loop and consider count($tablevalues)-1 to be the last key of your array.
So that $tablevalues[count($tablevalues)-1] is your last <td>.
Why dont you use jQuery?It has provisions to do something like that.