如何在c#中将office文件(docx,xl​​sx)转换为google格式

时间:2017-08-18 15:20:35

标签: c# google-drive-api google-docs

任何人都有共享的方式将docx,xl​​sx,pptx转换为程序化的谷歌格式。我正在通过Google Drive API上传并使用c#与用户分享。每当有人编辑文件时,每次创建一个重复的文档。

我想在上传时转换文件。所以我可以将转换后的文件分享给每个人。

我正在使用Google Drive v3 api。

下载代码:

private static System.IO.MemoryStream DownloadFile(DriveService service, string fileID)
    {
        var request = service.Files.Get(fileID);
        var stream = new System.IO.MemoryStream();

        // Add a handler which will be notified on progress changes.
        // It will notify on each chunk download and when the
        // download is completed or failed.
        request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>
        {
            switch (progress.Status)
            {
                case Google.Apis.Download.DownloadStatus.Downloading:
                    {
                        Console.WriteLine(progress.BytesDownloaded);
                        break;
                    }
                case Google.Apis.Download.DownloadStatus.Completed:
                    {
                        Console.WriteLine("Download complete.");
                        //SaveStream(stream, saveTo);
                        break;
                    }
                case Google.Apis.Download.DownloadStatus.Failed:
                    {
                        Console.WriteLine("Download failed.");
                        break;
                    }
            }
        };
        request.Download(stream);
        return stream;
    }

    private static void SaveStream(System.IO.MemoryStream stream, string saveTo)
    {
        using (System.IO.FileStream file = new System.IO.FileStream(saveTo, System.IO.FileMode.Create, System.IO.FileAccess.Write))
        {
            stream.WriteTo(file);
        }
    }

1 个答案:

答案 0 :(得分:0)

这是让你开始我的朋友的事情。查看Basic uploadsImporting to Google Docs types,因为它会向您展示如何上传和转换某些文件类型为Google格式。

var fileMetadata = new File()
{
    Name = "My Report",
    MimeType = "application/vnd.google-apps.spreadsheet"
};
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream("files/report.csv",
                        System.IO.FileMode.Open))
{
    request = driveService.Files.Create(
        fileMetadata, stream, "text/csv");
    request.Fields = "id";
    request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);