Question

I am working on creating excel from my SQL server, the problem is that the row is in one cell. I want the output to be on each cell in the same row. That will make it easier to edit and sum data.

This is the query and the output in the sql server:

enter image description here

Output in the Excel file:

enter image description here

Code:

$sql = "
SELECT measurements.title as Tittel, routines.value as Verdi, convert(VARCHAR(10), routines.time, 108) as Tid, pools.name as Basseng, emps.user_name as Ansatt
FROM routines, measure_routine, measurements, pools, emps
WHERE routines.id = measure_routine.routine_id
AND measure_routine.measure_id = measurements.id
AND (measurements.title  Like 'T_%') AND measure_routine.pool_id=pools.id AND routines.emp_id=emps.id 
AND pools.name = 'Hovedbasseng' 
ORDER BY routines.date, routines.time;
";

 $result=sqlsrv_query($conn,$sql) or die("Couldn't execute query:<br>" . sqlsrv_error(). "<br>" . sqlsrv_errno()); 

$file_ending = "xls";
$reals=array();
//header info for browser
header("Content-Type: application/csv");    
header("Content-Disposition: attachment; filename=test.csv");  
header("Pragma: no-cache"); 
header("Expires: 0");
/*******Start of Formatting for Excel*******/   
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character

$i=0;
foreach( sqlsrv_field_metadata( $result ) as $fieldMetadata ) {    
       echo $fieldMetadata["Name"]+"\t";
       if($fieldMetadata["Type"]=="real")//$fieldMetadata["Type"]=== SQL_REAL
       {
           $reals[] = $i;
       }
       $i++;
}


print("\n");    
//end of printing column names  
//start while loop to get data

while($row = sqlsrv_fetch_array($result))
{
   $schema_insert = "";
   for($j = 0; $j < sqlsrv_num_fields($result); $j++)
   {
      if ($row[$j] != "") {
         if (in_array($j, $reals)) {
            $schema_insert .= str_replace(".",",", $row[$j]) . $sep;
         } else {
            $schema_insert .= $row[$j] . $sep;
         }
      }
      else
         $schema_insert .= "" . $sep;
   }
   $schema_insert = str_replace($sep."$", "", $schema_insert);
   $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
   $schema_insert .= "\t";
   print(trim($schema_insert));
   print "\n";
}

?>
Was it helpful?

Solution

Do this: Open phpMyadmin Log in open table you want to grab click export choose file type you want to export it as

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top