Jump to content

[SOLVED] Export to Excel issue


Hybride

Recommended Posts

I've been trying to export MySQL data to an excel / CSV file, and I have it pretty much populating the Excel properly with the data; however, the Excel sheet also includes the entire HTML formatting + CSS/JS coding before the export code. I've tried getting rid of it with strip_tags, to no avail. Is it because the export code is to the middle of the file? I tried to move it into the header, but that didn't work either. Any ideas?

 

echo '<input type="submit" value="Export to Excel" name="export">';
if (isset($_POST['export'])) {
$query = "SELECT * FROM manual WHERE name='$name'";
$result = mysql_query($query) OR die(mysql_error());		

while($row = mysql_fetch_array($result)) {
     $contents = $row[name] . ",";
      $contents .= $row[date] . ",";
      $contents .= $row[physalbum] . ",";
      $contents .= $row[digalbum] . ",";
      $contents .= $row[physinsales] . ",";
     $contents .= strip_tags($contents);
   }
   Header("Content-Disposition: attachment; filename=$name.csv");
   print $contents;

	}

Link to comment
https://forums.phpfreaks.com/topic/77747-solved-export-to-excel-issue/
Share on other sites

I too had problems with this in the past.  I ended up just using the php function to create a file and then write to it.  I then created a URL to the file and just clicked on the link.  Firefox then came up with a .csv file and asked me which program I wanted to use to open it.  I just selected excel and it worked.  Here is how you create a file..

 

//Create a new CSV file..
$csvFileName = "name.csv";
$csvFileName = fopen($ourFileName, 'w') or die("can't open file");

 

Then just write a little bit into the file..

//write data to file...
$stringData = "data, data, data\n";
fwrite($csvFileName, $stringData);
$stringData = "more, more, more\n";
fwrite($csvFileName, $stringData);

 

When finished make sure you close the file

fclose($csvFileName);

Try that out and let me know if that works any better

I too had problems with this in the past.  I ended up just using the php function to create a file and then write to it.  I then created a URL to the file and just clicked on the link.  Firefox then came up with a .csv file and asked me which program I wanted to use to open it.  I just selected excel and it worked. 

Try that out and let me know if that works any better

 

Ahh, I see. My problem was that I was directly linking to the file rather than creating then linking. That fixed it up, much thanks!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.