UnicodeEncodeError:' ascii'编解码器不能对字符u' \ xa0'进行编码。位置37:序数不在范围内(128)

时间:2015-12-12 09:12:05

标签: python xlrd

执行以下代码时出现此错误:

<repositories>
    <repository>
        <id>ibiblio-central-repo</id>
        <layout>default</layout>
        <name>ibiblio-central-repo</name>
        <releases>
            <checksumPolicy>warn</checksumPolicy>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </releases>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
        <url>http://maven.ibiblio.org/maven2/</url>
    </repository>

    <repository>
        <id>oschina-central-repo</id>
        <layout>default</layout>
        <name>oschina-central-repo</name>
        <releases>
            <checksumPolicy>warn</checksumPolicy>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </releases>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
        <url>http://maven.oschina.net/content/groups/public/</url>
    </repository>

    <repository>
        <id>oschina-central-repo-3rd-party</id>
        <layout>default</layout>
        <name>oschina-central-repo-3rd-party</name>
        <releases>
            <checksumPolicy>warn</checksumPolicy>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </releases>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
        <url>http://maven.oschina.net/content/repositories/thirdparty/</url>
    </repository>
</repositories>

此时我收到错误:def csvFromExcel(path): 'This is for converting Delights.xlsx sheets into sheetName.csv ' wb = xlrd.open_workbook(path) print wb.nsheets sheetNames = [] sheetNames = wb.sheet_names() print sheetNames for sheetName in sheetNames: sh = wb.sheet_by_name(sheetName) csvFile = open("processed/"+sheetName+'.csv', 'wb') wr = csv.writer(csvFile, quoting=csv.QUOTE_ALL) for rownum in xrange(sh.nrows): wr.writerow(sh.row_values(rownum)) csvFile.close() if __name__ == "__main__": path = 'toBeProcess/Delights.xlsx' csvFromExcel(path)

有没有人知道如何解决它。

1 个答案:

答案 0 :(得分:0)

我已使用encode('utf-8')

解决了这个问题
def csvFromExcel(path):
    'This is for converting Delights.xlsx sheets into sheetName.csv '
    wb = xlrd.open_workbook(path)
    print wb.nsheets
    sheetNames = []
    sheetNames = wb.sheet_names()
    print sheetNames
    for sheetName in sheetNames:
        sh = wb.sheet_by_index(2)
        csvFile = open("processed/"+sheetName+".csv", 'wb')
        wr = csv.writer(csvFile, quoting=csv.QUOTE_ALL)

        for rownum in xrange(sh.nrows):
            wr.writerow(
                 list(x.encode('utf-8') if type(x) == type(u'') else x
                      for x in sh.row_values(rownum)))
        csvFile.close()

if __name__ == "__main__":
    path = 'toBeProcess/Delights.xlsx'
    csvFromExcel(path)