4

How can I convert the array/json into an Excel file (Office Open XML)?

$result = mysql_query($query);
$rows = Array();
while($row = mysql_fetch_assoc($result)) {
    array_push($rows, $row);
}
echo json_encode(Array(
    "data" => $rows
));
ilhan
  • 8,311
  • 31
  • 114
  • 194
  • 1
    There's not a magical convert_to_excel() function, but I believe there are a few libraries for this. Very worst case, the standard for Excel's file format has been published by MS. – Corbin Jun 26 '12 at 09:15

1 Answers1

0

You can use ajax xlsx lib to create an excel file from json.

<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.13.1/xlsx.full.min.js"></script>
  </head>
  <body>
    <button onclick="exportData()">Export</button>
    <script>
      function exportData(){
        filename = 'reports.xlsx';
        data = [{'Market': "IN",' New Arrivals': "6", 'Upcoming Appointments': "2", 'Pending - 1st Attempt': "4"},
                {'Market': "KS/MO",' New Arrivals': "4", 'Upcoming Appointments': "4", 'Pending - 1st Attempt': "2"},
                {'Market': "KS/MO",' New Arrivals': "4", 'Upcoming Appointments': "4", 'Pending - 1st Attempt': "2"},
                {'Market': "KS/MO",' New Arrivals': "4", 'Upcoming Appointments': "4", 'Pending - 1st Attempt': "2"}]
        var ws = XLSX.utils.json_to_sheet(data);
        var wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "People");
        XLSX.writeFile(wb, filename);
      }
    </script>
  </body>
</html>

Source : similiar question on stackoverflow