2012-09-12 44 views
1

我想從.csv文件創建電子表格。 代碼:如何從.csv文件創建谷歌驅動器電子表格?

static void Main() 
     { 
      String CLIENT_ID = "<MY ID>"; 
      String CLIENT_SECRET = "<MY SECRET>"; 

      var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET); 
      var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); 
      var service = new DriveService(auth); 

      File body = new File(); 
      body.Title = "My spread"; 
      body.Description = "A test spread"; 
      body.MimeType = "application/vnd.google-apps.spreadsheet"; 

      byte[] byteArray = System.IO.File.ReadAllBytes("spread.csv"); 
      System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); 

      service.Files.Insert(body, stream, "application/vnd.google-apps.spreadsheet").Upload(); 
     } 

     private static IAuthorizationState GetAuthorization(NativeApplicationClient arg) 
     { 
      string[] scopes = new string[] { "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/userinfo.profile" }; 
      IAuthorizationState state = new AuthorizationState(scopes); 
      state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl); 
      Uri authUri = arg.RequestUserAuthorization(state); 

      // Request authorization from the user (by opening a browser window): 
      Process.Start(authUri.ToString()); 
      Console.Write(" Authorization Code: "); 
      string authCode = Console.ReadLine(); 
      Console.WriteLine(); 

      // Retrieve the access token by using the authorization code: 
      return arg.ProcessUserAuthorization(authCode, state); 
     } 

插入文件並點擊它谷歌驅動器頁面後(登錄作爲所有者)我得到消息

「對不起 在這個網址的電子表格不能。找到。請確保您有正確的網址和電子表格的擁有者沒有刪除它」

當我改變Mime類型爲‘text/CSV’,插入文件,點擊它後,我得到消息 「無預覽vailable 此產品是使用Google雲端硬盤應用(MyApp'sName)創建的。 下載這個文件,或使用已安裝打開它的應用程序之一。「

我可以在這個文件(即一個與創建也右鍵點擊‘文本/ CSV’Mime類型),然後選擇選項」導出到谷歌文檔「,這給了我結果,我想達到 - 電子表格文件與我的.csv的文件內容。但這種間接的方法並不完全滿足我。是否有任何方法來使電子表格文件在谷歌驅動器,與從.csv文件的內容從我的應用程序直接?

+0

完整的源代碼示例任何最終的解決方案? – Kiquenet

回答

1

我不知道C#,但基礎上,它是Java的鏡像,行內

service.Files.Insert(body,stream, 「application/vnd.google-apps.spreadsheet」)。Upload();

你需要插入

.setConvert相當於(真)

也...

的MIME類型應是 「text/CSV」

1

我找到了答案:)

如何將文件編程轉換成相應的谷歌文檔格式:

var service = new DriveService(new BaseClientService.Initializer 
{ 
    ... 
}); 

... 

FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, _mimeType); 
request.Convert = true; 
request.Upload(); 
相關問題