python读取Excel指定单元格的值使⽤openpyxl实现
只⽀持xlsx⽂件,不⽀持xls
import openpyxl
def read_cell(io, sheet, cell='A2'):
"""
读取单元格
:param io: Excel⽂件路径
:param sheet: 读取哪⼀张表,str, int eg: 'Sheet1' or 0
:param cell: 读取哪⼀个单元格
:return: value --> str
"""
excel = openpyxl.load_workbook(io)
if isinstance(sheet, str):
ws = excel[sheet]
elif isinstance(sheet, int):python怎么读取excel某一列
name = excel.sheetnames[sheet]
ws = excel[name]
else:
raise TypeError('sheet must be int or str, not %s' % type(sheet))
val = ws[cell].value
if not val:
val = ""
return val
使⽤xlrd实现
只⽀持xls(version > 2.x),既⽀持xls⼜⽀持xlsx(version < 2.x)
import xlrd
def get_index(capital):
"""
⼤写字母(Excel列头)转数字
:param capital: 'A' --> 0, 'AA' --> 26
:return: int
"""
number = 0
capital = capital.upper()
for char in capital:
number = number * 26 + ord(char) - ord('A') + 1
return number - 1
def read_cell(io, sheet, cell='A1'):
"""
读取单元格
:param io: Excel⽂件路径
:param sheet: 读取哪⼀张表,str, int eg: 'Sheet1' or 0
:param cell: 读取哪⼀个单元格
:return: value --> str
"""
wb = xlrd.open_workbook(io)
if isinstance(sheet, str):
ws = wb.sheet_by_name(sheet)
elif isinstance(sheet, int):
ws = wb.sheet_by_index(sheet)
position = re.findall(r'[0-9]+|[A-Z]+', cell)
pos_col = position[0]
pos_row = int(position[1])
col_index = get_index(pos_col)
values = ws.col_values(col_index, start_rowx=pos_row - 1, end_rowx=pos_row)
if values:
val = values[0]
else:
val = ''
return val
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论