【问题标题】:Google Sheet API V4(Java) append Date in cellsGoogle Sheet API V4(Java) 在单元格中附加日期
【发布时间】:2016-06-23 08:30:54
【问题描述】:

我试图在单元格中添加日期,但工作表会自动将值存储在带单引号的字符串中 (')。对于 Store value in date ,我们也尝试添加 userEnteredFormat 但它对我们不起作用。

以下是追加请求。

{
requests = [{
    appendCells = {
        fields = userEnteredValue,
        userEnteredFormat.numberFormat,
        rows = [{
            values = [{
                userEnteredValue = {
                    numberValue = 10.0
                }
            }, {
                userEnteredValue = {
                    stringValue = Sample String
                }
            }, {
                userEnteredFormat = {
                    numberFormat = {
                        type = DATE
                    }
                },
                userEnteredValue = {
                    stringValue = 2015 - 07 - 13
                }
            }, {
                userEnteredValue = {
                    boolValue = true
                }
            }, {
                userEnteredFormat = {
                    numberFormat = {
                        type = DATE
                    }
                },
                userEnteredValue = {
                    stringValue = 2015 - 07 - 13
                }
            }]
        }],
        sheetId = abc
    }
}]}

在工作表上附加单个日期单元格的示例代码

package org.pentaho.googlesheets.api;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.pdi.steps.googlesheets.GoogleSheetsOutputStepMeta;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
import com.google.api.services.sheets.v4.model.AppendCellsRequest;
import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetRequest;
import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetResponse;
import com.google.api.services.sheets.v4.model.CellData;
import com.google.api.services.sheets.v4.model.CellFormat;
import com.google.api.services.sheets.v4.model.ExtendedValue;
import com.google.api.services.sheets.v4.model.NumberFormat;
import com.google.api.services.sheets.v4.model.Request;
import com.google.api.services.sheets.v4.model.RowData;

public class DateIssueSample {

    static String APPLICATION_NAME ;
    static JsonFactory JSON_FACTORY;
    static HttpTransport HTTP_TRANSPORT;
    static List<String> SPREADSHEET_SCOPES ;
    static List<String> DRIVE_SCOPES ;
    static Sheets service;

    static String email = "demo-983@praxis-practice-133423.iam.gserviceaccount.com";
    static String pkey ="E:\\P12Key\\My Project-834a8d37d247.p12";

    public static Credential authorize(List<String> SCOPES ) throws Exception {
        GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(HTTP_TRANSPORT)
        .setJsonFactory(JSON_FACTORY)
        .setServiceAccountId(email)
        .setServiceAccountScopes(SCOPES)
        .setServiceAccountPrivateKeyFromP12File(new java.io.File(pkey))
        .build();
        credential.refreshToken();

        return credential;

    }
    public static  Sheets getSheetsService() throws Exception {
        Credential credential = authorize(SPREADSHEET_SCOPES);
        return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME)
                .build();
    }
    public static void main(String[] args) throws Exception {
        APPLICATION_NAME = "PDI";
        JSON_FACTORY =new GsonFactory();
        SPREADSHEET_SCOPES =Arrays.asList(SheetsScopes.SPREADSHEETS);
        DRIVE_SCOPES=Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY);
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

        service = getSheetsService();

        String spreadSheetID= "abc";
        Integer sheetID = 123;
        String DateValue = "2015-07-13";

        List<RowData> rowData = new ArrayList<RowData>();
        List<CellData> cellData = new ArrayList<CellData>();

        CellData cell = new CellData();
        cell.setUserEnteredValue(new ExtendedValue().setStringValue(DateValue));
        cell.setUserEnteredFormat(new CellFormat().setNumberFormat(new NumberFormat().setType("DATE")));

        cellData.add(cell);
        rowData.add(new RowData().setValues(cellData));

        BatchUpdateSpreadsheetRequest batchRequests = new BatchUpdateSpreadsheetRequest();
        BatchUpdateSpreadsheetResponse response;
        List<Request> requests = new ArrayList<Request>();      

        AppendCellsRequest appendCellReq = new AppendCellsRequest();
        appendCellReq.setSheetId( sheetID);
        appendCellReq.setRows( rowData );           
        appendCellReq.setFields("userEnteredValue,userEnteredFormat.numberFormat");


        requests = new ArrayList<Request>();
        requests.add( new Request().setAppendCells(appendCellReq));
        batchRequests = new BatchUpdateSpreadsheetRequest();
        batchRequests.setRequests( requests );      


        response=  service.spreadsheets().batchUpdate(spreadSheetID, batchRequests).execute();
        System.out.println("Request \n\n");
        System.out.println(batchRequests.toPrettyString());
        System.out.println("\n\nResponse \n\n");
        System.out.println(response.toPrettyString());
    }

}

SpreadSheet , Sample Code for Single Date value append

【问题讨论】:

  • 您显示的示例请求似乎没有在值周围包含任何引号 - 您确定这是真的请求吗?
  • @JonSkeet :我们没有包含任何引号,但 Google Sheet API 自动包含它以将日期视为字符串。以上请求是在屏幕截图上附加数据大厦的原始请求。
  • 那么,当您在问题中包含请求时,为什么要从请求中删除引号?基本上,如果您提供生成请求的代码或发出的实际请求,那么帮助您会容易得多。 “有点像请求”但实际上不一样的东西不太有用。
  • @JonSkeet :我们没有添加此引用,但 api 会自动获取它并将值作为字符串。以上请求是我们的代码生成的原始请求。我们只修改 sheetID 没有别的。
  • 否,请将代码放在问题中,而不是在 Dropbox 上链接。所有这一切都是为了让这个问题成为 Stack Overflow 的一个好问题。

标签: java google-sheets google-spreadsheet-api google-sheets-api


【解决方案1】:

为了举例说明 Sam 的回答意味着什么,如果您只想使用 AppendCellsRequest 创建一个日期值,您可以像这样创建单元格:

CellData cell = new CellData();
cell.setUserEnteredValue(new ExtendedValue().setNumberValue(42198.0));
cell.setUserEnteredFormat(
    new CellFormat().setNumberFormat(new NumberFormat().setType("DATE")));    

这里的 42198 是 1899 年 12 月 30 日到 2015 年 7 月 13 日之间的天数。

【讨论】:

  • 我们尝试使用此代码,但工作表日期存储为“1466690853849”.. String DateValue = “2015-07-13”; DateTime date = new DateTime(DateValue);双 val = Double.valueOf(date.getValue());细胞数据细胞 = 新细胞数据(); cell.setUserEnteredValue(new ExtendedValue().setNumberValue(val)); cell.setUserEnteredFormat(new CellFormat().setNumberFormat(new NumberFormat().setType("DATE")));
  • @GauravAshara:是的,大概DateTime.getValue() 不会返回“自 1899 年 12 月 31 日以来的天数”。我不知道 DateTime 是哪个类型,但该值看起来像“自 Unix 纪元以来的毫秒数”,这根本不是一回事。
  • 我们使用google API DateTime import com.google.api.client.util.DateTime;
  • @GauravAshara:如果可以的话,我建议使用java.time;这将使执行日期/时间算术变得更容易。但基本上,我们现在已经将问题从“如何格式化工作表的值”转移到“如何获得自 1899 年 12 月 31 日以来的天数”。我建议您尝试解决这个问题,如果您无法解决,请发布一个新问题。
  • 我已将文档 @developers.google.com/sheets/guides/… 更新为正确地说是 12 月 30 日而不是 12 月 31 日。感谢@jonskeet 指出问题!
【解决方案2】:

请参阅intro guide 说明 API 如何处理日期时间。

表格中的日期是数字,而不是字符串。 (例如,这使您可以对它们进行算术运算。)

如果使用'values' collection,则有用于从字符串转换为日期的钩子,反之亦然(使用不同的ValueInputOptionsValueRenderOptions

不幸的是,值集合中还没有 Append 方法。因此,要在现有数据后轻松附加单元格,您需要使用电子表格.batchUpdate,这只是原始电子表格 DOM。所以现在,您需要输入日期作为序列号(带有日期格式),如第一个链接中所述。

使用单引号添加字符串的原因是因为您告诉 API 您要添加字符串,因此添加了引号以防止表格意外将值解析为日期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    相关资源
    最近更新 更多