1

我想从 .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);
        }

插入文件并在 google-drive 页面上单击它(登录为所有者)后,我收到消息

“很抱歉。无法找到此 URL 中的电子表格。请确保您拥有正确的 URL 并且电子表格的所有者没有将其删除”

当我将 MimeType 更改为“text/csv”并插入文件时,单击它后,我收到消息 “没有可用的预览 此项目是使用 Google Drive 应用程序 (MyApp'sName) 创建的。下载此文件或使用其中一个您安装的应用程序可以打开它。”

我还可以右键单击此文件(使用“text/csv”MimeType 创建的文件)并选择“导出到 Google Docs”选项,这给了我想要达到的结果 - 带有我的 .csv 文件内容的电子表格文件. 但是这种间接的方法并不能完全满足我。有什么方法可以在谷歌驱动器上制作电子表格文件,内容来自我的应用程序中的 .csv 文件?

4

2 回答 2

1

我不知道 c#,但在它反映 Java 的基础上,在行内

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

你需要插入相当于

.setConvert(真)

还 ...

mimetype 应该是“text/csv”

于 2012-09-12T15:14:57.580 回答
1

我找到了答案:)

如何以编程方式将文件转换为适当的 Google 文档格式:

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

...

FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, _mimeType);
request.Convert = true;
request.Upload();
于 2014-10-03T14:16:52.117 回答