简体   繁体   中英

export to CSV percentage formatting

Having an issue with the formatting of the percentages in an exported CSV file.

Here is the process that grabs the data and sends it back to JQuery to be exported:

<?php
  include('include/sessions.php');

  $date_begin = date("Y-m-d", strtotime($_POST['date_begin']));
  $date_end = date("Y-m-d", strtotime($_POST['date_end']));

  $sql = "SELECT table1.services, table1.port
          sum(case when TIMESTAMPDIFF(HOUR,table2.berth,table1.performance) <= -12 then 0 else 1 end) ON_TIME,
          count(table1.port) TTL_CALLS,
          round((sum(case when TIMESTAMPDIFF(HOUR,table2.berth,table1.performance) <= -12 then 0 else 1 end)/count(table1.port))*100,1) as ON_TIME_PCT
          FROM
            table1
          Left Outer Join table2 ON table1.voyage = table2.voyage AND table1.port = table2.port
          WHERE
            date( table1.performance ) >= '$date_begin' AND
            date( table1.performance ) <= '$date_end'";

  $query = mysqli_query($dbc, $sql) or die(mysqli_error($dbc));

  $out = array();
  while($row = $query->fetch_assoc()){
    $out[] = $row;
  }
  echo json_encode($out);
  
?>

The field I am referring to is ON_TIME_PCT.

Using the above, when running the query in the dB itself, the results of the query for the field in reference can vary between 100.0 or 50.0.

When the data is exported, the cells initially look like 100 or 50.

When changing the format in Excel to show the full percentage, the numbers look like 10000% or 5000%.

I am not sure why that is happening.

Here is the code that I am using to export to CSV:

$('#byPortService').on('click', function(){

  var date_begin = $('#date_begin').val();
  var date_end = $('#date_end').val();

  $.post('api/byPortService.php', {date_begin:date_begin,date_end:date_end}, function(data){
    JSONToCSVConvertor(data, "BY PORT SERVICE REPORT - DATE RANGE: "+date_begin+" - "+date_end+"", true);
  });
});

Here is the JSONToCSVConvertor function:

function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel){
  var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
  var CSV = '';
  CSV += ReportTitle + '\r\n\n';
  if (ShowLabel) {
    var row = "";
    for (var index in arrData[0]) {
      row += index + ',';
    }
    row = row.slice(0, -1);
    CSV += row + '\r\n';
  }
  for (var i = 0; i < arrData.length; i++) {
    var row = "";
    for (var index in arrData[i]) {
      row += '"' + arrData[i][index] + '",';
    }
    row.slice(0, row.length - 1);
    CSV += row + '\r\n';
   }
   if (CSV == '') {
     alert("Invalid data");
     retirn;
   }
   var fileName = ReportTitle.replace(/ /g,"_");
   var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
   var link = document.createElement("a");
   link.href = uri;
   link.style = "visibility:hidden";
   link.download = fileName + ".csv";
   document.body.appendChild(link);
   link.click();
   document.body.removeChild(link);
}

Is there any way that I can export the percentages so that they retain the decimal?

I don't want the user to have to manually do it on the Excel side.

Like mentionned in comments, make sure the values are between 0 and 1 .

To keep a certain amount of decimal in PHP, use number_format()

<?php
$number = 0.5;
formatted number = number_format($number, 2);  // 0.50
?>

I was able to solve the problem by changing this line:

round((sum(case when TIMESTAMPDIFF(HOUR,table2.berth,table1.performance) <= -12 then 0 else 1 end)/count(table1.port))*100,1) as ON_TIME_PCT

To this:

concat(round((sum(case when TIMESTAMPDIFF(HOUR,table2.berth,table1.performance) <= -12 then 0 else 1 end)/count(table1.port))*100,0),'%') as ON_TIME_PCT

And now the fields are showing 100% or 50% even after formatting Excel.

Thank you all for your help. Upvotes for everyone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM