Google API實戰與操作

Google api實戰與操作

      • 一. Google API 權限配置
      • 二. 操作API
        • 2.1 引入依賴
        • 2.2 導入代碼

Google官網

實現一套用java程序控制GoogleAPI實現自動生成監控日報等功能,具體能操作Gsheet及document

一. Google API 權限配置

打開上面官網,新建項目
在這里插入圖片描述
啟用API
在這里插入圖片描述
搜索sheet及document
在這里插入圖片描述

在這里插入圖片描述.點擊試用后進入API界面 點擊創建憑據
在這里插入圖片描述
創建OAuth 客戶端重定向記得跟下面配置一樣,因為需要先登錄才能授權
在這里插入圖片描述
生成完成后點擊下載到本地,相當于你的Token
在這里插入圖片描述

這時候就可以生成表格了

二. 操作API

2.1 引入依賴

<!--        google文檔--><dependency><groupId>com.google.api-client</groupId><artifactId>google-api-client</artifactId><version>1.31.2</version></dependency><dependency><groupId>com.google.apis</groupId><artifactId>google-api-services-sheets</artifactId><version>v4-rev614-1.18.0-rc</version></dependency><dependency><groupId>com.google.oauth-client</groupId><artifactId>google-oauth-client-jetty</artifactId><version>1.31.4</version></dependency><dependency><groupId>com.google.cloud</groupId><artifactId>google-cloud-storage</artifactId></dependency><!-- https://mvnrepository.com/artifact/com.google.apis/google-api-services-drive --><dependency><groupId>com.google.apis</groupId><artifactId>google-api-services-drive</artifactId><version>v3-rev197-1.25.0</version></dependency><dependency><groupId>com.google.apis</groupId><artifactId>google-api-services-docs</artifactId><version>v1-rev20220609-2.0.0</version></dependency><dependency><groupId>org.gitlab4j</groupId><artifactId>gitlab4j-api</artifactId><version>5.2.0</version></dependency><dependency><groupId>com.google.cloud</groupId><artifactId>libraries-bom</artifactId><version>25.4.0</version><type>pom</type><scope>import</scope></dependency>

將上面生成的Token導入項目

2.2 導入代碼

package com.shopee.bank.business.utility;import com.baomidou.mybatisplus.extension.api.R;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.docs.v1.Docs;
import com.google.api.services.docs.v1.DocsScopes;
import com.google.api.services.docs.v1.model.*;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
import com.google.api.services.sheets.v4.model.Spreadsheet;
import com.google.api.services.sheets.v4.model.SpreadsheetProperties;
import com.google.api.services.sheets.v4.model.UpdateValuesResponse;
import com.google.api.services.sheets.v4.model.ValueRange;
import com.google.common.collect.Lists;
import io.swagger.models.auth.In;
import lombok.Builder;
import lombok.Data;import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;/*** @author kaiyi.wang* @ClassName GoogleSheetUtil.java* @Description* @createTime 2022/07/05*/
public class GoogleUtil {private static final String APPLICATION_NAME = "Quickstart";private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();private static final String TOKENS_DIRECTORY_PATH = "tokens";private static final List<String> SCOPES_READ = Lists.newArrayList(SheetsScopes.SPREADSHEETS_READONLY);private static final List<String> SCOPES_CREATE = Lists.newArrayList(SheetsScopes.SPREADSHEETS,DriveScopes.DRIVE_FILE);private static final List<String> DOCS_SCOPES = Lists.newArrayList(DocsScopes.all());public static final String PHFoldID="1msqpxxxxx9vx82Cln";public static final String IDFoldID="1VyxuzHxxxxxxxHR";/*** TODO 下載的應用授權文件,這里記得換成自己的授權文件*/private static final String CREDENTIALS_FILE_PATH = "/credentials.json";private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT,List<String> scopes) throws IOException {// Load client secrets.InputStream in = GoogleUtil.class.getResourceAsStream(CREDENTIALS_FILE_PATH);if (in == null) {throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);}GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));// Build flow and trigger user authorization request.GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH))).setAccessType("offline").build();LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");}public static void main(String[] args) throws IOException, GeneralSecurityException {
//       createSpreadsheet("測試");
//      }public static String createSpreadsheet(String title) throws IOException, GeneralSecurityException {final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();// Create the sheets API clientSheets service = new Sheets.Builder(new NetHttpTransport(),GsonFactory.getDefaultInstance(),getCredentials(HTTP_TRANSPORT,SCOPES_CREATE)).setApplicationName("Sheets samples").build();// Create new spreadsheet with a titleSpreadsheet spreadsheet = new Spreadsheet().setProperties(new SpreadsheetProperties().setTitle(title));spreadsheet = service.spreadsheets().create(spreadsheet).setFields("spreadsheetId").execute();// Prints the new spreadsheet idSystem.out.println("Spreadsheet ID: " + spreadsheet.getSpreadsheetId());return spreadsheet.getSpreadsheetId();}public static void updateSheet(String sid,List<List<Object>> writeData,String dimension,String writeRange) throws IOException, GeneralSecurityException {final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();// Create the sheets API clientSheets service = new Sheets.Builder(new NetHttpTransport(),GsonFactory.getDefaultInstance(),getCredentials(HTTP_TRANSPORT,SCOPES_CREATE)).setApplicationName("Sheets samples").build();writeSomething(writeData, service, sid,dimension,writeRange);}//COLUMNS / ROWSpublic static void writeSomething(List<List<Object>> myData, Sheets service, String sid,String dimension,String writeRange) {try {
//            String writeRange = "工作表1!A:F";ValueRange vr = new ValueRange().setValues(myData).setMajorDimension(dimension);UpdateValuesResponse raw = service.spreadsheets().values().update(sid, writeRange, vr).setValueInputOption("RAW").execute();} catch (Exception e) {e.printStackTrace();}}@Data@Builderpublic static class VInfo{private String name;private String count;}/*** A1 符號* 一種語法,用于使用包含工作表名稱以及使用列字母和行號的開始和結束單元格坐標的字符串來定義單元格或單元格范圍。在引用絕對范圍的單元格時,此方法最常見且最有用。** 顯示示例* Sheet1!A1:B2指的是 Sheet1 前兩行中的前兩個單元格。* Sheet1!A:A指 Sheet1 第一列中的所有單元格。* Sheet1!1:2指 Sheet1 前兩行中的所有單元格。* Sheet1!A5:A指的是工作表 1 第一列的所有單元格,從第 5 行開始。* A1:B2指第一個可見工作表的前兩行中的前兩個單元格。* Sheet1指 Sheet1 中的所有單元格。* 'My Custom Sheet'!A:A指名為“我的自定義工作表”的工作表第一列中的所有單元格。帶有空格、特殊字符或字母數字組合的工作表名稱需要單引號。* 'My Custom Sheet'指“我的自定義工作表”中的所有單元格。* 提示:在可能的情況下,為電子表格中的對象使用不同的名稱。例如,A1 指的是第一個可見工作表中的單元格 A1,而“A1”指的是名為 A1 的工作表中的所有單元格。同樣,Sheet1 引用 Sheet1 中的所有單元格。但是,如果有一個名為“Sheet1”的命名范圍,則 Sheet1 指的是命名范圍,而“Sheet1”指的是工作表。* @throws GeneralSecurityException* @throws IOException*/// 讀取電子表格public static void readSheet() throws GeneralSecurityException, IOException {// Build a new authorized API client service.final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();final String spreadsheetId = "1XiZZT2ctZ8JMjGy2GYOPmsat5CD24U9r0wo6vro-z9Q";    // 這個是官方的 spreadsheetId,讀取自己的Google Sheet換成對應ID即可final String range = "aml_process_tab!A1:F12"; // 讀取的表格范圍,命名規范: {sheet表名稱}!{開始單元格}:{結束單元格}Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT,SCOPES_READ)).setApplicationName(APPLICATION_NAME).build();ValueRange response = service.spreadsheets().values().get(spreadsheetId, range).execute();List<List<Object>> values = response.getValues();if (values == null || values.isEmpty()) {System.out.println("No data found.");} else {for (List row : values) {for (int i = 0; i < row.size(); i++) {System.out.print(row.get(i) + "\t\t");}System.out.println("");}}}public static List<String> moveFileToFolder(String fileId, String folderId)throws IOException, GeneralSecurityException {final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT,SCOPES_CREATE)).setApplicationName(APPLICATION_NAME).build();// Retrieve the existing parents to removeFile file = service.files().get(fileId).setFields("parents").execute();StringBuilder previousParents = new StringBuilder();for (String parent : file.getParents()) {previousParents.append(parent);previousParents.append(',');}try{// Move the file to the new folderfile = service.files().update(fileId, null).setAddParents(folderId).setRemoveParents(previousParents.toString()).setFields("id, parents").execute();return file.getParents();}catch (GoogleJsonResponseException e) {// TODO(developer) - handle error appropriatelySystem.err.println("Unable to move file: " + e.getDetails());throw e;}}/*** 復制文件到目標目錄下* @param documentId 目標docs* @param foldID 遷移目錄* @param copyName 復制文件后的名字* @throws GeneralSecurityException* @throws IOException*/public static String copyDocs(String documentId,String foldID,String copyName) throws GeneralSecurityException, IOException {final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
//        Docs service = new Docs.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT,DOCS_SCOPES))
//                .setApplicationName(APPLICATION_NAME)
//                .build();Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT,DOCS_SCOPES)).setApplicationName(APPLICATION_NAME).build();File copyMetadata = new File().setName(copyName);File documentCopyFile =service.files().copy(documentId, copyMetadata).execute();String documentCopyId = documentCopyFile.getId();moveFileToFolder(documentCopyId, foldID);return documentCopyId;}private static Docs getDocsService()  {final NetHttpTransport HTTP_TRANSPORT;Docs service;try {HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();service = new Docs.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT,DOCS_SCOPES)).setApplicationName(APPLICATION_NAME).build();} catch (GeneralSecurityException | IOException e) {throw new RuntimeException(e);}return service;}/*** 指定索引處插入文本* @param docsId* @param index 文字的索引 從0開始* @param text 插入文本* @throws IOException*/public static void updateDocs(String docsId, Integer index, String text) throws IOException {Docs service = getDocsService();List<Request> requests = new ArrayList<>();requests.add(new Request().setInsertText(new InsertTextRequest()
//                .setText("07.18~07.24").setText(text)
//                .setLocation(new Location().setIndex(2))));.setLocation(new Location().setIndex(index))));BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest().setRequests(requests);BatchUpdateDocumentResponse response = service.documents().batchUpdate(docsId, body).execute();System.out.println("updated: "+response.getDocumentId());}/*** 最末尾處插入空表格* @param docsId* @throws IOException*/public static void insertSheetInDocs(String docsId) throws IOException {Docs service = getDocsService();List<Request> requests = new ArrayList<>();requests.add(new Request().setInsertTable(new InsertTableRequest().setEndOfSegmentLocation(new EndOfSegmentLocation()).setRows(3).setColumns(3)));BatchUpdateDocumentRequest body =new BatchUpdateDocumentRequest().setRequests(requests);BatchUpdateDocumentResponse response =service.documents().batchUpdate(docsId, body).execute();}/*** docs中表格插入數據 必須倒著寫不然索引會變(代碼內已處理)* @param docsId 操作文檔* @param indexOfTable 文檔中第幾個表* @param data 行數據* @param row 寫入第幾行數據 注意第一可能為標題* @throws IOException 表格若有數據會報錯*/public static void updateDocsSheetRow(String docsId,Integer indexOfTable,List<Object> data,int row) throws IOException {Docs service = getDocsService();// 獲取結構Document document = service.documents().get(docsId).execute();List<StructuralElement> tables = document.getBody().getContent().stream().filter(e -> e.getTable() != null).collect(Collectors.toList());if(indexOfTable>=tables.size()){throw new IllegalArgumentException("out of size");}// 獲取tableStructuralElement table = tables.get(indexOfTable);// 拿到table行索引List<Integer> indexs = table.getTable().getTableRows().get(row).getTableCells().stream().map(TableCell::getStartIndex).collect(Collectors.toList());Collections.reverse(indexs);Collections.reverse(data);List<Request> requests = insertRowList(indexs, data);BatchUpdateDocumentRequest body =new BatchUpdateDocumentRequest().setRequests(requests);BatchUpdateDocumentResponse response = service.documents().batchUpdate(docsId, body).execute();}public static List<Request> insertRowList(List<Integer> reIndex,List<Object> rowData){int i=0;List<Request> rows=new ArrayList<>();for (Object e : rowData) {Request request = new Request().setInsertText(new InsertTextRequest().setText(String.valueOf(e)).setLocation(new Location().setIndex(reIndex.get(i++)+1)));rows.add(request);}
//        Collections.reverse(rows);return rows;}}

注釋都有 湊活看看 下次詳細講解 拉取Grafana自動生成報表

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/42280.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/42280.shtml
英文地址,請注明出處:http://en.pswp.cn/news/42280.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【山河送書第七期】:《強化學習:原理與Python實戰》揭秘大模型核心技術RLHF!

《強化學習&#xff1a;原理與Python實戰》揭秘大模型核心技術RLHF&#xff01; 一圖書簡介二RLHF是什么&#xff1f;三RLHF適用于哪些任務&#xff1f;四RLHF和其他構造獎勵模型的方法相比有何優劣&#xff1f;五什么樣的人類反饋才是好反饋&#xff1f;六如何減小人類反饋帶來…

LVGL圖層的介紹

一.UI界面顯示的圖層 在lvgl開發的過程中&#xff0c;UI界面的顯示都是位于lv_sct_act()圖層 二.彈窗顯示 lvgl開發過程中&#xff0c;有些窗口有可能在任何時候顯示&#xff0c;比如錯誤信息彈窗&#xff0c;外部觸發的一些中斷。 這個時候&#xff0c;這些窗口不能建立在lv_s…

web前端開發基礎入門html5+css3+js學習筆記(一)

目錄 1.第一個前端程序2.前端工具的選擇與安裝3.VSCode開發者工具快捷鍵4.HTML5簡介與基礎骨架4.1 HTML5的DOCTYPE聲明4.2 HTML5基本骨架4.2.1 html標簽4.2.2 head標簽4.2.3 body標簽4.2.4 title標簽4.2.5 meta標簽 5.標簽之標題5.1 快捷鍵5.1 標題標簽位置擺放 6.標簽之段落、…

LeetCode每日一題——2682. 找出轉圈游戲輸家

n 個朋友在玩游戲。這些朋友坐成一個圈&#xff0c;按 順時針方向 從 1 到 n 編號。從第 i 個朋友的位置開始順時針移動 1 步會到達第 (i 1) 個朋友的位置&#xff08;1 < i < n&#xff09;&#xff0c;而從第 n 個朋友的位置開始順時針移動 1 步會回到第 1 個朋友的位…

leetcode 377. 組合總和 Ⅳ

2023.8.17 本題屬于完全背包問題&#xff0c;乍一看和昨天那題 零錢兌換II 類似&#xff0c;但細看題目發現&#xff1a;今天這題是排列問題&#xff0c;而“零錢兌換II”是組合問題。排列問題強調順序&#xff0c;而組合順序不強調順序。 這里先說個結論&#xff1a;先遍歷物品…

并查集、樹狀數組

并查集、樹狀數組、線段樹 并查集樹狀數組樹狀數組1 (單點修改&#xff0c;區間查詢)樹狀數組2 (單點查詢&#xff0c;區間修改) 并查集 【模板】并查集 題目描述 如題&#xff0c;現在有一個并查集&#xff0c;你需要完成合并和查詢操作。 輸入格式 第一行包含兩個整數 …

Scala中的Either的用法

在 Scala 中&#xff0c;Either 是一種表示兩種可能值的數據類型。它可以用來處理函數可能返回的兩種不同類型的結果&#xff0c;通常用于錯誤處理或者結果分支情況。Either 有兩個子類&#xff1a;Left 和 Right&#xff0c;其中 Left 通常用于表示錯誤或異常情況&#xff0c;…

1.物聯網LWIP網絡,TCP/IP協議簇

一。TCP/IP協議簇 1.應用層&#xff1a;FTP&#xff0c;HTTP&#xff0c;Telent&#xff0c;DNS&#xff0c;RIP 2.傳輸層&#xff1a;TCP&#xff0c;UDP 3.網絡層&#xff1a;IPV4&#xff0c;IPV6&#xff0c;OSPF&#xff0c;EIGRP 4.數據鏈路層&#xff1a;Ethernet&#…

YOLOv5改進系列(21)——替換主干網絡之RepViT(清華 ICCV 2023|最新開源移動端ViT)

【YOLOv5改進系列】前期回顧: YOLOv5改進系列(0)——重要性能指標與訓練結果評價及分析 YOLOv5改進系列(1)——添加SE注意力機制 YOLOv5改進系列(2

兩階段提交:詳解數據庫宕機引起的主從不一致問題、redolog與binlog的兩階段提交

0、基礎知識and問題 從基礎上我們了解&#xff1a; &#xff08;1&#xff09;redolog作為數據庫保證持久化的日志&#xff0c;在update事務提交后就會按一定的策略刷入磁盤中&#xff0c;在刷入后&#xff0c;即使數據庫斷電宕機&#xff0c;mysql也能從redolog中恢復數據到磁…

Matplotlib數據可視化(六)

目錄 1.繪制概率圖 2.繪制雷達圖 3.繪制流向圖 4.繪制極坐標圖 5.繪制詞云圖 1.繪制概率圖 from scipy.stats import norm fig,ax plt.subplots() plt.rcParams[font.family] [SimHei] np.random.seed() mu 100 sigma 15 x musigma*np.random.randn(437) num_bins …

【騰訊云 Cloud Studio 實戰訓練營】在線 IDE 編寫 canvas 轉換黑白風格頭像

關于 Cloud Studio Cloud Studio 是基于瀏覽器的集成式開發環境(IDE)&#xff0c;為開發者提供了一個永不間斷的云端工作站。用戶在使用Cloud Studio 時無需安裝&#xff0c;隨時隨地打開瀏覽器就能在線編程。 Cloud Studio 作為在線IDE&#xff0c;包含代碼高亮、自動補全、Gi…

winform 設置畫刷半透明

使用solidBrush新建畫刷&#xff0c;定義畫刷的顏色為透明色 Brush b new SolidBrush(Color.FromArgb(50, Color.Green)); 這里的50是透明度的設置&#xff0c;范圍從0-255&#xff1b; 0:無顏色 255:不透明 轉&#xff1a;c# 設置Brush 畫刷 透明_solidcolorbrush 透明色_…

git-fatal: No url found for submodule path ‘packages/libary‘ in .gitmodules

文章目錄 前言一、git submodule功能使用二、錯誤信息&#xff1a;三、解決方法&#xff1a;四、.gitmodules配置文件&#xff1a;總結 前言 最近在做vue項目&#xff0c;因為項目比較復雜&#xff0c;把功能拆分成很多子模塊&#xff0c;我們使用Git的submodule功能。遇到錯誤…

使用libvncserver庫快速搭建VNC服務端

文章目錄 VNC是什么libvncserver的優點和缺點構建libvncserver使用libvncserver搭建VNCServerX11模擬鼠標鍵盤操作libvncserver中處理鼠標鍵盤消息 VNC是什么 VNC(Virtual Network Computing)是一種使用遠程幀緩沖協議(RFB)的屏幕分享及遠程操作軟件。VNC的服務端可以通過RFP協…

Linux開機啟動程序添加root權限

Linux添加開機啟動程序 Debain、Ubuntu系列Linux開機之后會執行/etc/rc.local文件中的命令&#xff0c;所以&#xff0c;如果是想添加登陸用戶所具有權限的操作&#xff0c;可以在文件中exit 0之前添加開機自動執行的腳本命令。或者將執行腳本的權限修改為當前登錄用戶具有執行…

基于R語言APSIM模型進階應用與參數優化、批量模擬

隨著數字農業和智慧農業的發展&#xff0c;基于過程的農業生產系統模型在模擬作物對氣候變化的響應與適應、農田管理優化、作物品種和株型篩選、農田固碳和溫室氣體排放等領域扮演著越來越重要的作用。APSIM (Agricultural Production Systems sIMulator)模型是世界知名的作物生…

moodle單點登陸

在moodle/login添加sso.php <?phprequire(../config.php); require_once(lib.php);if($_SERVER[REQUEST_METHOD]==GET){$tokenId=$_GET[tokenId]; }else{$tokenId="fail";

C++新經典03--共用體、枚舉類型與typedef

共用體 共用體&#xff0c;也叫聯合&#xff0c;有時候需要把幾種不同類型的變量存放到同一段內存單元&#xff0c;例如&#xff0c;把一個整型變量、一個字符型變量、一個字符數組放在同一個地址開始的內存單元中。這三個變量在內存中占的字節數不同&#xff0c;但它們都從同…

idea 轉換為 Maven Project 的方法

選項&#xff1a; Add as Maven Project