GsheetController.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Exception;
  4. use Google\Service\Sheets\ValueRange;
  5. use Google_Client;
  6. use Illuminate\Console\Command;
  7. use Revolution\Google\Sheets\Facades\Sheets;
  8. use Revolution\Google\Sheets\Sheets as SheetsSheets;
  9. use Illuminate\Http\Request;
  10. use Illuminate\Support\Facades\DB;
  11. class GsheetController extends Controller
  12. {
  13. public function testGsheet(){
  14. $sql = 'SELECT uid, name_first, name_last FROM client';
  15. $sqlParams = [];
  16. $values = $this->getValues($sql, $sqlParams);
  17. $spreadsheetId = '1jRCkukeSfZufY8gpKSGYgv9cgeDbA1ZYP4pKJhyPP_o';
  18. $sheetName = 'Sheet1';
  19. return $this->exportToGsheet($sql, $sqlParams, $spreadsheetId, $sheetName);
  20. }
  21. private function exportToGsheet($sql, $sqlParams, $spreadsheetId, $sheetName){
  22. $client = $this->getApiClient();
  23. $service = new \Google\Service\Sheets($client);
  24. $values = $this->getValues($sql, $sqlParams);
  25. $range = $sheetName.'!A1:V1';
  26. $body = new ValueRange([
  27. 'values' => $values
  28. ]);
  29. $params = [
  30. 'valueInputOption' => 'RAW'
  31. ];
  32. $result = $service->spreadsheets_values->append($spreadsheetId, $range, $body, $params);
  33. return $result;
  34. }
  35. function getApiClient(){
  36. $KEY_FILE_LOCATION = storage_path('stag-gsheets-d9ead2f78b4b.json');
  37. $client = new Google_Client();
  38. $client->setApplicationName("My Rooster Admin");
  39. $client->setAuthConfig($KEY_FILE_LOCATION);
  40. $client->setScopes([\Google\Service\Sheets::DRIVE, \Google\Service\Sheets::SPREADSHEETS]);
  41. return $client;
  42. }
  43. private function getValues($sql, $sqlParams){
  44. $values = [];
  45. $raws = DB::select($sql, $sqlParams);
  46. if(!count($raws)){
  47. throw new \Exception("No data");
  48. }
  49. $firstRaw = $raws[0];
  50. $headers = [];
  51. foreach($firstRaw as $k => $val) {
  52. $headers[] = $k;
  53. }
  54. $values[] = $headers;
  55. foreach($raws as $raw){
  56. $rawStr = '';
  57. foreach($headers as $header ){
  58. $rawStr = $rawStr.$raw->$header.'~~';
  59. }
  60. $values[] = explode('~~', $rawStr);
  61. }
  62. return $values;
  63. }
  64. }