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.
Related
This is kind of silly and unecessary but also kind of a waste of time since I am doing this every day. But I am wondering if there is a way to export data using PHP to CSV that does not require the use of the text import wizard when opening the file in excel.
Currently my code looks like this which I think seems to be pretty standard every where I look:
header("Content-type: text/csv");
header('Content-Disposition: attachment; filename=exported_shipments_'.date("Ymd").'.csv');
header("Pragma: no-cache");
header("Expires: 0");
echo "name" . "\t";
echo "address_1" . "\t";
echo "address_2" . "\t";
echo "city" . "\t";
echo "province_code" . "\t";
echo "postal_code" . "\t";
echo "country_code" . "\t";
echo "phone" . "\t";
echo "package_contents" . "\t";
echo "description" . "\t";
echo "value" . "\t";
echo "value_currency" . "\t";
echo "order_store" . "\t";
echo "order_id" . "\t";
echo "package_type" . "\t";
echo "size_x" . "\t";
echo "size_y" . "\t";
echo "size_z" . "\t";
echo "size_unit" . "\t";
echo "weight" . "\t";
echo "weight_unit" . "\t";
echo "postage_type" . "\t";
echo "signature_requested" . "\t";
echo "insurance_requested" . "\t";
echo "ship_date" . "\t";
echo "\n";
And so on.
Is there anything I can do so that excel recognizes that I want it to be delimited right away instead of having to use the wizard?
You're using tab, not comma to separate the CSV. You also can force the Content-Type to application/vnd.ms-excel, and set the extension to .xls, it'll open with Excel and automatically import CSV.
You can use this code to do this:
<?php
header ( "Content-type: application/vnd.ms-excel");
header ( "Content-Disposition: attachment; filename=exported_shipments_" . date ( "Ymd") . ".xls");
header ( "Pragma: no-cache");
header ( "Expires: 0");
$data = array ();
$data[] = "name";
$data[] = "address_1";
$data[] = "address_2";
$data[] = "city";
$data[] = "province_code";
$data[] = "postal_code";
$data[] = "country_code";
$data[] = "phone";
$data[] = "package_contents";
$data[] = "description";
$data[] = "value";
$data[] = "value_currency";
$data[] = "order_store";
$data[] = "order_id";
$data[] = "package_type";
$data[] = "size_x";
$data[] = "size_y";
$data[] = "size_z";
$data[] = "size_unit";
$data[] = "weight";
$data[] = "weight_unit";
$data[] = "postage_type";
$data[] = "signature_requested";
$data[] = "insurance_requested";
$data[] = "ship_date";
$fp = fopen ( "php://output", "w");
fputcsv ( $fp, array_values ( $data), ",", "\"");
fclose ( $fp);
?>
I am using WP_List_Table class to make a table at back end which fetches records from myCustomTable. Is there any feature/plugin available to export the single & multiple rows to CSV format. I have tried so many plugin but they all come up with the whole table export.
Thanks
yes you can do. this an an example of my code where i use to get the DB table to excel formate. you just replace the DB connection, table,table fields, and query as required this code may helps you
<?php
include '../common/inc.common.php';//db connectivity
$class=$_REQUEST['class_id'];//get the class id
$line .= "\n";
$filename='../app/class_export_student_hsc.csv';// file name
$fp = fopen($filename, "w");
$sql="SELECT t1 . * ,y.aca_year
FROM (
SELECT name,fathername,school_name,edu_disctrict,revenue_disctrict,nationality,religion,caste,castetype,gender,dob,dobword,mark1,stat
FROM **myCustomTable**
)t1, academic_years y
WHERE t1.academic_year=y.refid
AND t1.class =$class
";
$studentArray=$Cobj->run_query($sql);
$line = "";
foreach($studentArray as $name => $valuee) {
$comma = "";
foreach($valuee as $key2 => $value){
$line .= $comma . '"' . str_replace('"', '""', $key2) . '"';
$comma = ",";
}
$line .= "\n";
break;
}
foreach($studentArray as $name => $valuee) {
$comma = "";
foreach($valuee as $key2 => $value){
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
}
$line .= "\n";
}
fputs($fp, $line);
fclose($fp);
if (file_exists($filename)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
}
?>
I wrote a utility to export a report from database to xls file. The database had some utf-8 characters which were not being converted into unreadable text when i wrote it to excel. I found a strange solution that if i post the first column first cell as specifically "ID#", it writes perfectly. Rest whatever i do with other columns, doesnt matter. BUT if i put anything else other than ID#, it prints unreadable rows.
For example when I put up ID# in first cell of first row, this is what i get
which is perfect.
But if i put anything else in the first cell, this is what happens.
Here is the code.
function generate_excel_report($filename, $header_array, $column_names, $data, $attachment_column, $correct_answer_column = FALSE, $insert_correct_answer = False) {
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel;charset=UTF-8");
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
for ($i = 0; $i < count($header_array); $i++) {
echo $header_array[$i] . "\t";
}
echo "\n";
$j = 0;
foreach ($data as $row) {
$k = 0;
for ($i = 0; $i < count($header_array); $i++) {
if ($i == $attachment_column) {
if ($row['attachment_type'] != '') {
echo '"' . $row['attachment_url'] . '"' . "\t";
} else {
echo '"' . $row[$column_names[$k]] . '"' . "\t";
$k++;
}
} else if ($i == $correct_answer_column && $insert_correct_answer) {
echo '"' . $row['option_' . $row['correct_answer']] . '"' . "\t";
} else {
if ($i == 0) {
echo '"' . ++$j . '"' . "\t";
} else {
echo '"' . $row[$column_names[$k]] . '"' . "\t";
$k++;
}
}
}
echo "\n";
}
}
I have absolutely no idea why it is doing so...Anyone can help here?
Thanks
This is because Excel thinks that Text files starting with IDxxx are in SYLK Format.
See e.g. here
You can with Id oder 'ID (with apostrophe) but not ID.
I m trying to fetch data from xml file then write it in CSV file.In generated file its put so many blank line after each record .
<?php
header("Content-Type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=spreadsheet.xls");
$url = 'test.xml'; // xml file location with file name
if (file_exists($url)) {
$xml = simplexml_load_file($url);
echo 'item_no' . "\t" . 'description' . "\t" . 'price' . "\t" . 'base_qty' . "\t" . 'var_qty' . "\t" . 'base_price_1' . "\t\n";
foreach ($xml->record as $books) {
$array_count = count($books);
for ($key = 0; $key < $array_count; $key++) {
echo $books->item_no[$key]."\t" . $books->description[$key]."\t" . $books- >price[$key]."\t" . $books->base_qty[$key] . "\t" . $books->var_qty[$key] . "\t" . $books->base_price_1[$key] . "\t" . "\n";
}
}
}
?>
Make sure the \n is not printed at the last record
<?php
header("Content-Type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=spreadsheet.xls");
$url = 'test.xml'; // xml file location with file name
$output = "";
if (file_exists($url)) {
$xml = simplexml_load_file($url);
$output.= 'item_no' . "\t" . 'description' . "\t" . 'price' . "\t" . 'base_qty' . "\t" . 'var_qty' . "\t" . 'base_price_1' . "\t\n";
foreach ($xml->record as $books) {
$array_count = count($books);
for ($key = 0; $key < $array_count; $key++) {
$output.= $books->item_no[$key]."\t" . $books->description[$key]."\t" . $books- >price[$key]."\t" . $books->base_qty[$key] . "\t" . $books->var_qty[$key] . "\t" . $books->base_price_1[$key] . "\t" . "\n";
}
}
echo rtrim($output);
}
?>
Am tryng to export data to csv file from mysql. I took the following script but the $result variable have error : mysql_num_fields tells the argument supplied is not valid
$filename = 'myfile.csv';
$result = db_query("SELECT * FROM {loreal_salons}");
drupal_set_header('Content-Type: text/csv');
drupal_set_header('Content-Disposition: attachment; filename=' . $filename);
$count = mysql_num_fields($result);
for ($i = 0; $i < $count; $i++) {
$header[] = mysql_field_name($result, $i);
}
print implode(',', $header) . "\r\n";
while ($row = db_fetch_array($result)) {
foreach ($row as $value) {
$values[] = '"' . str_replace('"', '""', decode_entities(strip_tags($value))) . '"';
}
print implode(',', $values) . "\r\n";
unset($values);
}
If you don't mind using a temporary file, you can do:
SELECT *
INTO OUTFILE '/tmp/myfile.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM loreal_salons
as your query, then simply do:
header('Content-type: text/csv');
header('Content-disposition: attachment; filename=myfile.csv');
readfile('/tmp/myfile.csv');
unlink('/tmp/myfile.csv');
exit();