how to merge cells in excel using php? - php

using php i exported report in excel.But got stuck in merging cells.
i want to merge the first 10 cells to dispaly the Name of the Company.
The variable which has the company name is in one cell, tried to merge the cells but i cudn't...

I used this function to export,
where $query variable holds the mysql query which is sent as a parameter,
and in $fieldname variable, array of fieldnames to display header.
everything is ok, n works properly.
one thing i cudn't do was merging cells....
function to_excel_export($query,$fieldName)
{
$filename = date('d-m-Y');
$headers = '';
$data = '';
$obj =& get_instance();
if ($query->num_rows() == 0)
{
echo '<p>The table appears to have no data.</p>';
}
else
{
for($i=0;$i<sizeof($fieldName);$i++)
{
$headers .= $fieldName[$i] . "\t";
}
foreach ($query->result() as $row)
{
$line = '';
foreach($row as $value)
{
if ((!isset($value)) OR ($value == ""))
{
$value = "\t";
}
else
{
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line)."\n";
}
$data = str_replace("\r","",$data);
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=$filename.xls");
$compName = 'C O M P A N Y - N A M E ';
echo $compName."\n\n";
echo $headers."\n".$data;
}
}
$compName = 'C O M P A N Y - N A M E ';
echo $compName."\n\n";
how to merge the cells to display the name which is in $compName variable.

You're not creating an Excel file, you're creating a CSV file (tab separated in this case), and that format does NOT support any kind of formatting (font, color, even merging cells isn't an option).... and you're not even using PHP's built-in fputcsv() function to do so :(
Simply giving a file an extension of .xls doesn't make it an Excel file. MS Excel is capable of reading CSV files, but some versions of Excel will actually warn you that the format isn't correct when you load it.
Create a proper Excel BIFF or OfficeOpenXML file using one of the many libraries available to do so (such as PHPExcel), and then you'll be able to set formatting such as cell background colours.

Related

Simple HTML DOM Memory issue

I'm trying to use PHP Simple HTML Dom Parser to parse some information from SQL query results. But it seems, that there is some HUGE memory problem with it. I create an html table using the SQL query results and then export the html table to a csv file. I am really new to this so my code is not the most efficient one. When I my query results are small the csv file is created successfully. But when the query results are large, the exported csv file does not have any sql results and instead shows this :
Fatal error: Call to a member function find() on boolean in /opt/lampp/htdocs/test.php on line 101
This is my function that takes the sqlresult and creates an html table and then exports it into a csv file:
echo sql_to_html_table($sqlresult, $delim="\n" );
function sql_to_html_table($sqlresult, $delim="\n") {
// starting table
include_once('simple_html_dom.php');
$htmltable = "<table>" . $delim ;
$counter = 0 ;
// putting in lines
//while( $row = $sqlresult->mysqli_fetch_assoc() ){
while($row = mysqli_fetch_assoc($sqlresult)) {
if ( $counter===0 ) {
// table header
$htmltable .= "<tr>" . $delim;
foreach ($row as $key => $value ) {
$htmltable .= "<th>" . $key . "</th>" . $delim ;
}
$htmltable .= "</tr>" . $delim ;
$counter = 22;
}
// table body
$htmltable .= "<tr>" . $delim ;
foreach ($row as $key => $value ) {
$htmltable .= "<td>" . $value . "</td>" . $delim ;
}
$htmltable .= "</tr>" . $delim ;
}
// closing table
$htmltable .= "</table>" . $delim ;
// return
//return( $htmltable ) ;
$html = str_get_html($htmltable);
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename=sample.csv');
$fp = fopen("php://output", "w");
foreach($html->find('tr') as $element)
{
$td = array();
foreach( $element->find('th') as $row)
{
$td [] = $row->plaintext;
}
fputcsv($fp, $td);
$td = array();
foreach( $element->find('td') as $row)
{
$td [] = $row->plaintext;
}
fputcsv($fp, $td);
}
fclose($fp);
}
I have tried throwing an exception after $html = str_get_html($htmltable); like this:
if (!str_get_html($htmltable)) {
throw new exception('exception') ;
}
and when I try to run the code my browser gives me this error:
Fatal error: Uncaught exception 'Exception' with message 'exception' in /opt/lampp/htdocs/test.php:96 Stack trace: #0 /opt/lampp/htdocs/test.php(62): sql_to_html_table(Object(mysqli_result), '\n') #1 {main} thrown in /opt/lampp/htdocs/test.php on line 96
Looking at a copy of simple_html_dom.php from SourceForge, this sounds like expected behavior for a sufficiently big HTML string. I see that str_get_html() has a check that will cause it to return false if the size of the string is greater than MAX_FILE_SIZE. And MAX_FILE_SIZE is defined with:
define('MAX_FILE_SIZE', 600000);
So it looks like simple_html_dom won't handle any string bigger than about 600kb. Since that's a built-in limitation, I guess your options are to either try to change the limit and see what happens or use a different library.
Alternatively, you could just skip the HTML portion altogether. If you need to generate the HTML for other purposes, that's fine, but there's no reason you can't bypass this problem by just building the CSV directly from the database results rather than from the HTML.
Maybe this is a little easier to understand:
function sql_to_csv($sqlresult, $delim = "\n") {
// Loop each result into a csv row string
while($row = mysqli_fetch_assoc($sqlresult)) {
// Create/reset a var to hold the csv row content
$csvRow = '';
// Append each column value comma separated
// Be warned of column values containing commas
foreach ($row AS $columnValue) {
$csvRow .= $columnValue . ',';
}
// Remove the trailing comma from the final column
rtrim($csvRow, ',');
// Send your CSV row to the browser
echo $csvRow . $delim;
}
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename=sample.csv');
}
There are various issues with this approach not limited to, large output buffers, columns with multi-commas ...etc I recognise these problems but wanted to give an early approach to the solution instead of a large block of text.
The easiest way to debug PHP code is to run it with de-bugg outputting, the following may help you if the above is not useful:
var_dump($variable);
exit;
This will enable you to see the contents of the variable at run time, and may give better indication to your exception, given the line-number in your exceptions.
Goodluck.

exporting MYSQL fectched row into csv in php

Following is a part of my php program which is written to fetch rows from mysql table from input IDs. But I wanted to get the result directly to '.csv' file. I know php has built in function for that, but I could not include it effectively. So can anyone give a direction for export to csv using advanced php function?
$file = fopen("fetched.csv","w");
for($i=0;$i<=$len;$i++)
{
$lo = $locus[$i];
mysqli_select_db($conn,"microarray");
$query = mysqli_query("SELECT * FROM anatomy WHERE locus_id = "$lo"");
while ($row = mysqli_fetch_row($query))
{
}
}
You don't necessarily need an "advanced php function". A csv file is just a sequence of comma separated columns. Try this out.
function addRowToCsv(& $csvString, $cols) {
$csvString = implode(',', $cols) . PHP_EOL;
}
$csvString = '';
$first = true;
while ($row = mysqli_fetch_assoc($query)) {
if ($first === true) {
$first = false;
addRowToCsv($csvString, array_keys($row));
}
addRowToCsv($csvString, $row);
}
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyCsvFile.csv');
echo $csvString;
Notice that the first argument to addRowToCsv is passed by reference. This is not required and you could easily use a return value, but this is just how I would do it.
-- Edit --
I just noticed you are saving the output to a file rather than serving it as a download. If that is what you want to do then use the above but replace
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyCsvFile.csv');
echo $csvString;
With..
file_put_contents('MyCsvFile.csv', $csvString);

Export Mysql Data into MS Excel Using a Link\Button in PHP

I am a newbie to PHP and need help in exporting a selected content from Mysql Table to MS Excel using PHP. I need this done by a click of a button or a link.
Below is a piece of code I have done so far but I am consistently getting a warning as "Cannot modify header information - headers already sent". Also suggest a good way to export table on a click of a button\link. Thanks
//Export Contents
$header = '';
$data = '';
$fields = mysql_num_fields($sql);
//fetch header
for($i=0; $i < $fields; $i++)
{
$header .= mysql_field_name($sql, $i)."\t";
}
//fetch data each row, store on tabular row data
while($row = mysql_fetch_row($sql))
{
$line = '';
foreach($row as $value)
{
if(!isset($value) || $value == "")
{
$value = "\t";
}
else
{
$value = str_replace('"', '""', $value);
$value = '"'.$value.'"'."\t";
}
$line .= $value;
}
$data .= trim($line)."\n";
$data = str_replace("\r", "", $data);
}
//Naming the excel sheet
$name = $customerFilter."_".date('d-m-y').".xls";
header("Content-type:application/vnd.ms-excel;name='excel'");
header("Content-Disposition: attachment; filename=$name");
header("Pragma: no-cache");
header("Expires: 0");
//Output Data
echo $header."\n\n".$data;
The mysql query
SELECT <column list>
FROM <table>
INTO OUTFILE '/tmp/somefilename.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
Then redirect to the file
if you got a "headers already sent" you have some output (whitespaces) before sending your excel headers. Please enshure that the <?php tag is the very first in your file.
Please read this thread: How to fix "Headers already sent" error in PHP
You should use a library like this http://phpexcel.codeplex.com/ to be able to output stable excel files.
Here is a hello world example for phpexcel:
http://phpexcel.codeplex.com/wikipage?title=Examples&referringTitle=Home

postgresql query result to csv prints current page's html code also

I am trying to output the results of a PostgreSQL query to CSV format using PHP.
On the main page is a link that sends the SQL statements as a string to another function in another PHP class, which in turn takes the SQL and executes the query using pg_query() and return the result sets.
My problem is that when I open the CSV file, all the results of my query are there, but at the end of the file I see the HTML code from the page that sent the query.
I looked at several StackOverflow posts, but to no avail.
Here is my code:
Main class:
$o .= '<p>You can convert the result set to CSV format to be opened in Excel.</p>';
$link = array('op1' => 'PatternExport', 'op2' => 'outputToCSV', 'id' => $pattern_id, 'data' => $pattern_SQL);
$o .= 'Download Query Results as CSV File';
Receiving class:
function outputToCSV()
{
$ptid = $this->oQS->getValue('id');
$sql = $this->oQS->getValue('data');
$href = $this->oQS->buildEncryptedURL(array('op1'=>'PatternManager', 'op2'=>'listPatterns'),'/aatsc/index.php');
$result = pg_query($sql);
// filename for download
$filename = "query_results_" . date('Ymd') . "_" . $ptid . ".csv";
$output = fopen('php://temp/maxmemory:' . (12*1024*1024), 'rw+');
foreach(pg_fetch_assoc($result,0) AS $field=>$value)
{
$output .= '' . $field . ',';
}
$output = rtrim($output,',') . "\n";
for($i=0;$i<pg_num_rows($result);$i++)
{
foreach(pg_fetch_assoc($result,$i) AS $field=>$value)
$output .= '' . $value . ',';
$output = rtrim($output,',') . "\n";
}
header("Content-Type: application/vnd.ms-excel;");
header("Content-Disposition: attachment; filename=\"$filename\";");
header("Pragma: no-cache");
print($output);
//$href = $this->oQS->buildEncryptedURL(array('op1'=>'PatternManager', 'op2'=>'listPatterns'),'/aatsc/index.php');
//header("Location: $href");
}
Could you tell me whether I am using the right approach to export query results to CSV, and what in my code is causing the whole HTML code to be streamed?
Thanks
You're generating $output twice, if you remove the foreach loop & fopen line, it should work.
You merely just need to issue the SQL COPY statement as follows:
COPY (select * from tbl) to stdout with csv header
resulting in:
col1,col2,col3
2013-05-22 07:28:59.732,192.168.1.67,3

exporting data from mysql to ms excel

I have the following code which I am using to export data from mysql database to microsoft excel
$result = $this->db->query($sql);
$num_fields = mysql_num_fields($result);
$header = "";
for($i = 0; $i < $num_fields; $i++ )
{
$header .= mysql_field_name($result,$i)."\t";
}
$data = "";
while($row = mysql_fetch_row($result))
{
$line = '';
foreach($row as $value)
{
if((!isset($value)) || ($value == ""))
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
/*if($code=="M"||$code=='m'){
$value="\n Total \t $total \t";
$data .=trim($value)."\n";
}*/
$data = str_replace("\r" , "" , $data);
if ($data == "")
{
$data = "\n No Record Found!n";
}
header("Cache-Control: ");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$label.xls\"");
header("Pragma: ");
header("Expires: 0");
print "$header\n$data";
where $result is a mysql resource.
When I run the program, before opening, excel issues a warning "the file you are trying to open, filename.xls, is in different format than specified by the extension, verify that the file is not corrupted and is from a trusted source before opening. Do you want to open the file now?"
I am stranded because after accepting to open the file, I see the data that I require, what I want is a way of making the format of data sent match the xls extension format. What should I do?. I am using ms office 2007
If you want to produce a real Excel file, use PHPExcel.
Your code produces a tab seperated ascii file - not an XLS file as you are claiming in the header.
Return the correct mimetype ("Content-Type: text/csv") and an appropriate file extension (e.g. ${label}.txt) and MSEscel will stop complaining.
(NB I'd stay well away from anything which writes native MSExcel files - even using MS's "open" xaml formats - sooner or later you'll run into horrible compatability problems).

Categories