像csv模块一样简单的Python.xlsx(officeopenxml)阅读器?

2024-10-01 07:33:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道一些pythonxlsx阅读器正在出现,但据我所见,它们似乎不像内置的csv模块那样直观。在

我想要的是一个可以执行以下操作的模块:

reader = xlsx.reader(open('/path/to/file'))

for sheet in reader:
    print 'In %s we have the following employees:' % (sheet.name)
    for row in sheet:
        print '%s, %s years old' % (row['Employee'], row['Age'])

有这样的读者吗?在


Tags: 模块csvpathinforopenxlsx内置
2条回答

目前,在alpha测试中,xlrd使用与xls相同的api来处理基本数据提取。如果有兴趣请给我发私人电子邮件。在

好吧,也许不是xlsx格式,但肯定是xls格式。从这里抓取xlrd:

http://www.python-excel.org/

下面是一些示例代码,让您了解使用它有多容易:

import xlrd

EMPLOYEE_CELL = 5
AGE_CELL = 6

reader = xlrd.open_workbook('C:\\path\\to\\excel_file.xls')
for sheet in reader.sheets():
    print 'In %s we have the following employees:' % (sheet.name)
    for r in xrange(sheet.nrows):
        row_cells = sheet.row(r)
        print '%s, %s years old' % (row_cells[EMPLOYEE_CELL].value, row_cells[AGE_CELL].value)

如果你能把文件保存为xls格式,你应该很好。我没有尝试上面的代码,但是如果不是100%正确的话,那就非常接近了。试试看,告诉我。在

编辑:

我猜你是在一台非windows的机器上这么做的。您可以使用类似PyODConverter的工具将文档从xlsx转换为xls,然后针对转换后的文件运行。像这样:

user@server:~# python DocumentConverter.py excel_file.xlxs excel_file.xlsuser@server:~# python script_with_code_above.py

再一次,还没有测试出来,但希望它能满足你的需要。在

相关问题 更多 >