I've got a PHP script that create a CSV file from a MySQL query. It outputs columns of data perfectly fine. The only problem is that Excel doesn't recognize the numbers as being "numbers" (that you can manipulate).
For example, if I have 2 cells with numbers 121.3 and 345.2 and I want to add them up, I will get an error. I've checked the formatting of my cells and made sure it's set to "Numbers", but still, the problem persists.
Here's my PHP script. Am I doing something wrong here ?
Thanks!
Expand|Select|Wrap|Line Numbers
- function WriteCsv($query) {
- include('databaseManager.php');
- $csv_terminated = "\n";
- $csv_separator = ";";
- $csv_enclosed = '"';
- $csv_escaped = "\\";
- $sql_query = $query;
- // Gets the data from the database
- $result = DatabaseManager::ExecuteQuery($query);
- $fields_cnt = mysql_num_fields($result);
- $schema_insert = '';
- for ($i = 0; $i < $fields_cnt; $i++)
- {
- $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
- stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
- $schema_insert .= $l;
- $schema_insert .= $csv_separator;
- } // end for
- $out = trim(substr($schema_insert, 0, -1));
- $out .= $csv_terminated;
- // Format the data
- while ($row = mysql_fetch_array($result))
- {
- $schema_insert = '';
- for ($j = 0; $j < $fields_cnt; $j++)
- {
- if ($row[$j] == '0' || $row[$j] != '')
- {
- if ($csv_enclosed == '')
- {
- $schema_insert .= $row[$j];
- } else
- {
- $schema_insert .= $csv_enclosed .
- str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
- }
- } else
- {
- $schema_insert .= '';
- }
- if ($j < $fields_cnt - 1)
- {
- $schema_insert .= $csv_separator;
- }
- } // end for
- $out .= $schema_insert;
- $out .= $csv_terminated;
- } // end whilexport.csv
- header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
- header("Content-Length: " . strlen($out));
- // Output to browser with appropriate mime type, you choose ;)
- header("Content-type: text/csv");
- //header("Content-type: text/csv");
- //header("Content-type: application/csv");
- header("Content-Disposition: attachment; filename=rapports_ventes_".date('Y-m-d').".csv");
- echo $out;
- exit;
- }