Как загрузить данные из файла xlsx, используя python - PullRequest
6 голосов
/ 02 апреля 2011

это мой файл xlsx:

enter image description here

и я хочу изменить эти данные на dict следующим образом:

{
    0:{
       'a':1,
       'b':100,
       'c':2,
       'd':10
    },
    1:{
       'a':8,
       'b':480,
       'c':3,
       'd':14
    }
...
}

поэтому кто-то знал библиотеку Python для этого и начинал со строки 124 и до конца строки 141,

спасибо

Ответы [ 4 ]

1 голос
/ 22 сентября 2014

Предположим, у вас были такие данные:

a,b,c,d
1,2,3,4
2,3,4,5
...

Один из многих возможных ответов в 2014 году:

import pyexcel


r = pyexcel.SeriesReader("yourfile.xlsx")
# make a filter function
filter_func = lambda row_index: row_index < 124 or row_index > 141
# apply the filter on the reader
r.filter(pyexcel.filters.RowIndexFilter(filter_func))
# get the data
data = pyexcel.utils.to_records(r)
print data

Теперь данные представляют собой массив словарей:

[{
   'a':1,
   'b':100,
   'c':2,
   'd':10
},
{
   'a':8,
   'b':480,
   'c':3,
   'd':14
}...
]

Документация может быть прочитана здесь

1 голос
/ 03 апреля 2011

Другой вариант - openpyxl . Я хотел попробовать это, но пока не дошел до этого, поэтому не могу сказать, насколько он хорош.

1 голос
/ 02 апреля 2011

Опции с xlrd :

(1) Ваш файл xlsx не выглядит очень большим;сохраните его как xls.

(2) Используйте xlrd плюс модуль бета-тестирования с болтовым креплением xlsxrd (найдите мой адрес электронной почты и спросите его);комбинация будет беспрепятственно считывать данные из файлов xls и xlsx (те же API; он проверяет содержимое файла, чтобы определить, является ли он xls, xlsx или самозванцем).

В любом случае что-то вроде (непроверенного) коданиже следует делать то, что вы хотите:

from xlrd import open_workbook
from xlsxrd import open_workbook
# Choose one of the above

# These could be function args in real live code
column_map = {
    # The numbers are zero-relative column indexes
    'a': 1,
    'b': 2,
    'c': 4,
    'd': 6,
    }
first_row_index = 124 - 1
last_row_index = 141 - 1
file_path = 'your_file.xls'

# The action starts here
book = open_workbook(file_path)
sheet = book.sheet_by_index(0) # first worksheet
key0 = 0
result = {}
for row_index in xrange(first_row_index, last_row_index + 1):
    d = {}
    for key1, column_index in column_map.iteritems():
        d[key1] = sheet.cell_value(row_index, column_index)
    result[key0] = d
    key0 += 1
0 голосов
/ 27 февраля 2014

Вот очень очень грубая реализация, использующая только стандартную библиотеку.

def xlsx(fname):
    import zipfile
    from xml.etree.ElementTree import iterparse
    z = zipfile.ZipFile(fname)
    strings = [el.text for e, el in iterparse(z.open('xl/sharedStrings.xml')) if el.tag.endswith('}t')]
    rows = []
    row = {}
    value = ''
    for e, el in iterparse(z.open('xl/worksheets/sheet1.xml')):
        if el.tag.endswith('}v'): # <v>84</v>
            value = el.text
        if el.tag.endswith('}c'): # <c r="A3" t="s"><v>84</v></c>
            if el.attrib.get('t') == 's':
                value = strings[int(value)]
            letter = el.attrib['r'] # AZ22
            while letter[-1].isdigit():
                letter = letter[:-1]
            row[letter] = value
        if el.tag.endswith('}row'):
            rows.append(row)
            row = {}
    return dict(enumerate(rows))
...