65.9K
CodeProject 正在变化。 阅读更多。
Home

Google 表格到 CSV 转换

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1投票)

2016 年 1 月 23 日

CPOL

2分钟阅读

viewsIcon

13382

downloadIcon

29

允许用户连接到 Google 表格并将其转换为 CSV

引言

我收到了来自市场部门的请求,他们正在Google文档(表格)中收集Google分析数据,并且希望将这些数据转换为CSV格式。因此,我创建了一个可配置的控制台应用程序来完成此任务。

此工具连接到Google文档,基于配置的设置,从表格单元格中获取数据,并将其转换为CSV文件。

背景

首先是Google文档的身份验证。有几种方法可以实现这一点,我使用了服务帐户进行身份验证。以下是配置服务帐户的链接:

您需要创建一个服务帐户并获取一个JSON密钥文件/证书以允许身份验证。每个Google服务帐户都有一个唯一的电子邮件ID,并确保允许此电子邮件访问您想要访问的表格。简而言之,只需将表格与此电子邮件ID共享即可。

Using the Code

为了使应用程序完全可配置,编写了一个节处理程序。它收集有关表格、工作表和要从Google文档中读取的单元格的信息。

<googleSpreadsheetSection>
    <googleSpreadsheets>
      <googleSpreadSheet name="Your Analytics" 
worksheetName="First" useAbsoluteRange="false" 
	range="A1:B11" startRow="0" endRow="0" 
	startColumn="0" endColumn="0" 
	outputFileName="file_one.csv"/>
      <googleSpreadSheet name="My Analytics" 
worksheetName="First" useAbsoluteRange="false" 
	range="A1:B11" startRow="0" endRow="0" 
	startColumn="0" endColumn="0" 
	outputFileName="file_two.csv"/>
    </googleSpreadsheets>
  </googleSpreadsheetSection>

有几个应用程序设置控制应用程序的行为。以下是您需要配置的应用程序设置。

 <appSettings>
    <add key="ApplicationName" value="AccessGoogleDriveDocs" />
    <add key="AppClientName" value=" AcessSpreadsheets" />
    <add key="JsonKeyFilePath" value="D:\Google\Key\AccessGoogleDocs.json" />
    <add key="ApplicationLogFilePath" value="D:\Google\Logs\ApplicationLog.txt" />
    <add key="CSVFolderPath" value="D:\Google\CSV" />
    <add key="NewLineCharacter" value="\n" />
    <add key="ColumnSeparator" value="," />
    <add key="EnableConsoleLogging" value="true" />
    <add key="UseFixedFileNames" value="false" />
  </appSettings>

重要设置的简短描述如下:

  • ApplicationName/AppClientName - 随意填写
  • JsonKeyFilePath - 创建Google服务帐户下的密钥时下载的文件路径。
  • NewLineCharacter - CSV文件中要使用的换行符
  • ColumnSeparator: CSV文件中要使用的列分隔符
  • UseFixedFileName: 当设置为true时,应用程序将使用节处理程序中定义的名称,否则将使用自动命名。
  • CSVFolderPath: 将生成CSV文件的路径

与Google文档的连接管理由GoogleSpreadsheetConnection类完成。

public GoogleSpreadsheetConnection(string applicationName, string filePath, string clientName)
{
  SpreadsheetConnection = new SpreadsheetsService(applicationName);
  SpreadsheetConnection.RequestFactory = AuthorizationHelper.GetRequestFactoryFromJson
	(filePath, clientName);
}

此类使用Google服务帐户创建到Google表格服务的连接,并使用JSON密钥文件凭据进行身份验证。使用AuthorizationHelper类创建RequestFactory实例,并将其分配给SpreadsheetService

public static GDataRequestFactory GetRequestFactoryFromJson(string filePath, string clientName)
{
   var jsonconfig = Newtonsoft.Json.JsonConvert.DeserializeObject
   				<authorizationinfo>(File.ReadAllText(filePath));
  var credential = new ServiceAccountCredential
  (new ServiceAccountCredential.Initializer(jsonconfig.ClientEmail)
            {
                Scopes = new[] 
                {"https://spreadsheets.google.com/feeds", 
                "https://docs.google.com/feeds" }
            }.FromPrivateKey(jsonconfig.PrivateKey));

            credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Wait();
            var requestFactory = new GDataRequestFactory(clientName);
            requestFactory.CustomHeaders.Add(string.Format
            	("Authorization: Bearer {0}", credential.Token.AccessToken));
            return requestFactory;
        }

关注点

我在处理此问题时犯了一个愚蠢的错误。我配置了Google服务帐户并配置了设置,但忘记将我的表格与Google服务帐户共享。所以请记住,当您创建一个服务帐户时,您将获得一个服务帐户的电子邮件ID,确保此电子邮件/帐户具有访问Google表格的权限。

历史

  • 2016年1月23日 - 首次发布
© . All rights reserved.