Jump to content

Writing to a spreadsheet


alanl1

Recommended Posts

Hi Professionals.

 

I am trying to write records from the DB into a spreadsheet, but when I open this there is only the titles, could I be missing something here.

 

I have tested my query in the backend database and it works fine.

 

Here is my code so far.

 

 

<?php
 
// Connect and query the database
 include("header.php");
  include("footer.php");
  include("ConnectDB.php");
$sql = "SELECT productdescription, activeqty FROM SARTable ORDER BY productdescription";
$stmt = sqlsrv_query( $conn, $sql);
/*  Check the database connection is good */
/*******************************************************/
 if( $conn === false) {
     die( print_r( sqlsrv_errors(), true) );
 }
 
 /*  Prepare the Create table statement. */
/*******************************************************/
 if(!$stmt = sqlsrv_prepare( $conn, $sql))
  {
   die( print_r( sqlsrv_errors(), true));
  }
  /*  Execute the Create table statement. */
 if( !sqlsrv_execute( $stmt))
  {
       die( print_r( sqlsrv_errors(), true));   
  }
// Pick a filename and destination directory for the file
// Remember that the folder where you want to write the file has to be writable
$newfilename = "Test.csv";
$filename = "C:\\inetpub\\wwwroot\\cleansed\\".$newfilename;
echo $filename;
// Actually create the file
// The w+ parameter will wipe out and overwrite any existing file with the same name
$handle = fopen($filename, 'w+');
// Write the spreadsheet column titles / labels
fputcsv($handle, array('productdescription','activeqty'));
 
// Write all the user records to the spreadsheet
foreach($stmt as $row)
{
    fputcsv($handle, array($row['productdescription'], $row['activeqty']));
}
 
// Finish writing the file
fclose($handle);
 sqlsrv_free_stmt( $stmt);
?>
 
Link to comment
Share on other sites

fantastic that works, just one thing though my output in the csv file is like so.

 

Column1, Column2, column1 data, column2 data,column1 data2ndrow, column2data2ndrow and so on
 
I would prefer it to be
 
Column1, Column2
column1 data, column2 data
column1 data2ndrow,column2data2ndrow
and so on

Is there a way to put in a new line character

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.