简体   繁体   English

使用 Python 从 OneDrive 下载 Excel 文件导致文件损坏

[英]Using Python to download an Excel file from OneDrive results in corrupt file

I am trying to download an excel file from a OneDrive location.我正在尝试从 OneDrive 位置下载 Excel 文件。 My code works okay to get the file, but the file is corrupt (I get an error message):我的代码可以正常获取文件,但文件已损坏(我收到一条错误消息):

import urllib2

data = urllib2.urlopen("enter url here")
with open('C:\\Video.xlsx', 'wb') as output:
    output.write(data.read())
output.close()
print "done"

I use the guest access to the excel file so that I don't have to work with authentication.我使用来宾访问 excel 文件,这样我就不必使用身份验证。 The resulting file seems to be 15KB, the original is 22KB.结果文件好像是15KB,原来是22KB。

You can't just download the Excel file directly from OneDrive using a URL.您不能仅使用 URL 直接从 OneDrive 下载 Excel 文件。 Even when you would share the file without any authorization, you'll probably still get a link to an intermediate HTML page, rather than the Excel binary itself.即使您在未经任何授权的情况下共享文件,您仍然可能会获得指向中间 HTML 页面的链接,而不是 Excel 二进制文件本身。

To download items from your OneDrive, you'll first need to authenticate and then pass the location of the file you're after.若要从 OneDrive 下载项目,您首先需要进行身份验证,然后传递您要查找的文件的位置。 You'll probably want to use the OneDrive REST API.您可能想要使用 OneDrive REST API。 The details on how to do that are documented on the OneDrive's SDK for Python GitHub page with some examples to get you started. OneDrive 的 SDK for Python GitHub 页面上记录了有关如何执行此操作的详细信息,并提供了一些示例以帮助您入门。

I got it.我明白了。 The url has the format below:网址格式如下:

'https://onedrive.live.com/view.aspx?cid=.....app=Excel' 'https://onedrive.live.com/view.aspx?cid=.....app=Excel'

So, all that I had to do was change "view" to "download" at that url, and used the code below:所以,我所要做的就是在那个 url 处将“视图”更改为“下载”,并使用以下代码:

import urllib.request

url = 'https://onedrive.live.com/view.aspx?cid=.....app=Excel'

urllib.request.urlretrieve(url, "test.xlsx")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM