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):
        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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM