在python中使用xlrd从xls中提取数据

时间:2014-10-31 10:22:14

标签: python excel list xlrd

我正在尝试从 .xls文件中提取数据并制作列表,但我将列表作为[u'elem1', u'elem2', u'elem3'],但如果我单独打印,则得到:

elem1
elem2
elem3

那是什么东西以及如何删除它?

这是我的代码......

from xlrd import open_workbook
xls=open_workbook('name.xls')
for sheets in xls.sheets():
    list1=[]
    for col in range(sheets.ncols):
        for rows in range(sheets.nrows):
            list1.append(sheets.cell(rows, col).value)
print(list1)
for i in list1:
    print(i)

4 个答案:

答案 0 :(得分:3)

您可以将文本定义为字符串,同时将数据附加到 list1.append(str(sheets.cell(rows,col).value)列表中以删除 [u& #39; 。代码将是:

   from xlrd import open_workbook
   xls=open_workbook('name.xls')
   for sheets in xls.sheets():
   list1=[]
   for col in range(sheets.ncols):
      for rows in range(sheets.nrows):
         list1.append(str(sheets.cell(rows, col).value))
   print(list1)
   for i in list1:
      print i

答案 1 :(得分:2)

假设您使用的是Python 2.x,u事情表明xlrd会为您提供unicode字符串(Excel字符串实际上是什么)。如果要在Python 2.7字符串中转换它们,则必须使用您使用的字符集对它们进行编码

假设您使用latin1(也称为iso-8859-1或(差异很小)windows-1252, 您可以通过以下方式转换latin1字符串列表中的unicode字符串列表:

strlist = [ elt.encode('latin1') for elt in list1 ]

或者如果您只有ASCII字符

strlist = [ str(elt) for elt in list1 ]

答案 2 :(得分:1)

我通过

解决了这个问题
str(variable_name)

答案 3 :(得分:0)

对于实际问题,开头的u不会影响你。你也可以使用它们,除非你有一些与以不同格式编码相关的问题。