当前位置:   article > 正文

Python酷库之旅-比翼双飞情侣库(15)_xlrd与xlrd3

xlrd与xlrd3

目录

一、xlrd库的由来

二、xlrd库优缺点

1、优点

1-1、支持多种Excel文件格式

1-2、高效性

1-3、开源性

1-4、简单易用

1-5、良好的兼容性

2、缺点

2-1、对.xlsx格式支持有限

2-2、功能相对单一

2-3、更新和维护频率低

2-4、依赖外部资源

三、xlrd库的版本说明

1、xlrd 1.2.0版本

2、xlrd 2.0.1版本

3、xlrd3(非官方名称)

四、如何学好xlrd库?

1、获取xlrd库的属性和方法

2、获取xlrd库的帮助信息

3、实战案例

3-144、判断工作表内是否有公式

3-145、判断某单元格区域是否为数组公式区域

3-146、判断工作表内是否有数组公式

3-147、判断单元格的计算公式是否引用了其他工作表数据

3-148、判断单元格的计算公式是否引用了其他工作簿数据

3-149、判断某单元格是否为合并单元格区域的一部分

3-150、获取单元格区域内的值

3-151、获取单元格内的前缀字符

3-152、判断单元格内的数字是否为文本字符

3-153、获取单元格的格式

3-154、获取单元格的字体(Font)对象

3-155、获取单元格的内部(Interior)对象

3-156、获取单元格的边框(Borders)对象

3-157、获取单元格边框线的状态

3-158、获取单元格的样式(Style)对象

3-159、获取单元格的条件格式

3-160、获取单元格的输入规则(有效性设置)

3-161、获取单元格的超链接

3-162、获取单元格的批注信息

3-163、获取单元格的大小(行高和列宽)

3-164、获取单元格的坐标

五、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

        在Excel中,通常所说的“情侣键”并非官方术语,而是对某些常用且经常成对出现的快捷键的一种形象化的称呼。其中,最为人熟知和广泛使用的“情侣键”是“Ctrl+C”和“Ctrl+V”。

1、Ctrl+C:这个快捷键的作用是“拷贝”或“复制”。当你在Excel中选中某个单元格、一行、一列或整个工作表的内容后,按下Ctrl+C键,这些内容就会被复制到计算机的剪贴板中,等待下一步的粘贴操作。
2、Ctrl+V:这个快捷键的作用是“粘贴”。在你按下Ctrl+C键将内容复制到剪贴板后,可以通过按下Ctrl+V键将这些内容粘贴到Excel中的另一个位置,这两个操作经常是连续进行的,因此Ctrl+C和Ctrl+V就像一对“情侣”,总是成对出现。

        除了这对常见的“情侣键”外,Excel中还有许多其他的快捷键可以帮助用户更高效地完成各种操作。然而,这些快捷键通常并没有像Ctrl+C和Ctrl+V那样形成特定的“情侣”关系。

        然而,今天我不再展开介绍“情侣键”,而是要重点推介Python中的“情侣库”,即xlrd和xlwt两个第三方库。

一、xlrd库的由来

        xlrd库是一种用于在Python中读取Excel文件的库,它的名称中的"xl"代表Excel,"rd"代表读取,其开发者是John Machin(注:库名字符拆分诠释,只是一种猜测)。

        xlrd最初是在2005年开始开发的,是基于Python的开源项目(下载:xlrd库官网下载)。

        由于Excel文件在数据处理和分析中的重要性,xlrd库填补了Python在处理Excel文件方面的空白,使得用户可以方便地在Python环境中读取Excel文件的内容,并进行进一步的数据操作和分析。

二、xlrd库

1、优点
1-1、支持多种Excel文件格式

        xlrd库支持多种Excel文件格式,包括`.xls`和`.xlsx`(在旧版本中),这使得无论数据存储在哪种格式的Excel文件中,用户都可以使用xlrd库来读取。


1-2、高效性

        xlrd库使用C语言编写,因此其性能非常高,即使面对非常大的Excel文件,xlrd也可以快速地读取其中的数据。


1-3、开源性

        xlrd是完全开源的,可以在GitHub等平台上找到其源代码,这使得任何人都可以根据自己的需求对其进行修改和扩展。


1-4、简单易用

        xlrd提供了简单直接的API来获取单元格数据、行列数等,使得从Excel文件中读取数据变得简单而高效。


1-5、良好的兼容性

        xlrd库适配多种Python版本,包括Python 2.7(不包括3.0-3.3)或Python 3.4及以上版本,这为用户提供了广泛的兼容性选择。

2、缺点
2-1、对.xlsx格式支持有限

        在xlrd 1.2.0之后的版本中(大约从2020年开始),xlrd库不再支持`.xlsx`文件格式,这限制了xlrd在新版Excel文件(主要是`.xlsx`格式)上的应用。


2-2、功能相对单一

        xlrd库主要专注于从Excel文件中读取数据,而不提供写入或修改Excel文件的功能,这使得在处理需要写入或修改Excel文件的任务时,用户需要结合其他库(如`openpyxl`或`xlwt`)使用。


2-3、更新和维护频率低

        由于xlrd库主要关注于读取Excel文件的功能,并且随着`.xlsx`格式的普及,其使用范围逐渐缩小,因此,xlrd库的更新和维护频率可能相对较低。


2-4、依赖外部资源

        在某些情况下,xlrd库可能需要依赖外部资源或库来完全发挥其功能,这可能会增加用户在使用xlrd库时的复杂性和不确定性。

        总之,xlrd库在读取Excel文件方面具有高效、开源和简单易用等优点,但在对`.xlsx`格式的支持、功能单一以及更新和维护频率等方面存在一些缺点,用户在选择使用xlrd库时需要根据自己的需求进行权衡和选择。

三、xlrd库的版本说明

        xlrd库适配的Python版本根据库的不同版本而有所不同。以下是针对几个主要版本的说明:

1、xlrd 1.2.0版本

1-1、适配Python>=2.7(不包括3.0-3.3)或Python>=3.4
1-2、该版本支持xlsx文件格式,并且是一个广泛使用的版本,因为它能够处理小到中等大小的Excel文件,并且具有较好的性能表现。

2、xlrd 2.0.1版本

2-1、适配Python>=2.7(不包括3.0-3.5)或Python>=3.6
2-2、该版本不再支持xlsx文件格式仅支持旧版的xls文件格式,因为在xlrd 2.0版本之后,xlrd移除了对xlsx格式的支持。

3、xlrd3(非官方名称)

        xlrd3是xlrd的开源扩展库,提供了对xlsx文件格式的支持,然而,请注意,xlrd3并不是xlrd的官方名称(下载:GitHub - Dragon2fly/xlrd3)。

四、如何学好xlrd库?

1、获取xlrd库的属性和方法

        用print()和dir()两个函数获取xlrd库所有属性和方法的列表

  1. # ['Book', 'FILE_FORMAT_DESCRIPTIONS', 'FMLA_TYPE_ARRAY', 'FMLA_TYPE_CELL', 'FMLA_TYPE_COND_FMT', 'FMLA_TYPE_DATA_VAL',
  2. # 'FMLA_TYPE_NAME', 'FMLA_TYPE_SHARED', 'Operand', 'PEEK_SIZE', 'Ref3D', 'XLDateError', 'XLRDError', 'XLS_SIGNATURE',
  3. # 'XL_CELL_BLANK', 'XL_CELL_BOOLEAN', 'XL_CELL_DATE', 'XL_CELL_EMPTY', 'XL_CELL_ERROR', 'XL_CELL_NUMBER', 'XL_CELL_TEXT', 'ZIP_SIGNATURE',
  4. # '__VERSION__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__',
  5. # '__spec__', '__version__',
  6. # 'biff_text_from_num', 'biffh', 'book', 'cellname', 'cellnameabs', 'colname', 'compdoc', 'count_records', 'decompile_formula',
  7. # 'dump', 'dump_formula', 'empty_cell', 'error_text_from_code', 'evaluate_name_formula', 'formatting', 'formula', 'info',
  8. # 'inspect_format', 'oBOOL', 'oERR', 'oNUM', 'oREF', 'oREL', 'oSTRG', 'oUNK', 'okind_dict', 'open_workbook', 'open_workbook_xls',
  9. # 'os', 'pprint', 'rangename3d', 'rangename3drel', 'sheet', 'sys', 'timemachine', 'xldate', 'xldate_as_datetime', 'xldate_as_tuple', 'zipfile']
'
运行
2、获取xlrd库的帮助信息

        用help()函数获取xlrd库的帮助信息

  1. Help on package xlrd:
  2. NAME
  3. xlrd
  4. DESCRIPTION
  5. # Copyright (c) 2005-2012 Stephen John Machin, Lingfo Pty Ltd
  6. # This module is part of the xlrd package, which is released under a
  7. # BSD-style licence.
  8. PACKAGE CONTENTS
  9. biffh
  10. book
  11. compdoc
  12. formatting
  13. formula
  14. info
  15. sheet
  16. timemachine
  17. xldate
  18. FUNCTIONS
  19. count_records(filename, outfile=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)
  20. For debugging and analysis: summarise the file's BIFF records.
  21. ie: produce a sorted file of ``(record_name, count)``.
  22. :param filename: The path to the file to be summarised.
  23. :param outfile: An open file, to which the summary is written.
  24. dump(filename, outfile=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, unnumbered=False)
  25. For debugging: dump an XLS file's BIFF records in char & hex.
  26. :param filename: The path to the file to be dumped.
  27. :param outfile: An open file, to which the dump is written.
  28. :param unnumbered: If true, omit offsets (for meaningful diffs).
  29. inspect_format(path=None, content=None)
  30. Inspect the content at the supplied path or the :class:`bytes` content provided
  31. and return the file's type as a :class:`str`, or ``None`` if it cannot
  32. be determined.
  33. :param path:
  34. A :class:`string <str>` path containing the content to inspect.
  35. ``~`` will be expanded.
  36. :param content:
  37. The :class:`bytes` content to inspect.
  38. :returns:
  39. A :class:`str`, or ``None`` if the format cannot be determined.
  40. The return value can always be looked up in :data:`FILE_FORMAT_DESCRIPTIONS`
  41. to return a human-readable description of the format found.
  42. open_workbook(filename=None, logfile=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, verbosity=0, use_mmap=True, file_contents=None, encoding_override=None, formatting_info=False, on_demand=False, ragged_rows=False, ignore_workbook_corruption=False)
  43. Open a spreadsheet file for data extraction.
  44. :param filename: The path to the spreadsheet file to be opened.
  45. :param logfile: An open file to which messages and diagnostics are written.
  46. :param verbosity: Increases the volume of trace material written to the
  47. logfile.
  48. :param use_mmap:
  49. Whether to use the mmap module is determined heuristically.
  50. Use this arg to override the result.
  51. Current heuristic: mmap is used if it exists.
  52. :param file_contents:
  53. A string or an :class:`mmap.mmap` object or some other behave-alike
  54. object. If ``file_contents`` is supplied, ``filename`` will not be used,
  55. except (possibly) in messages.
  56. :param encoding_override:
  57. Used to overcome missing or bad codepage information
  58. in older-version files. See :doc:`unicode`.
  59. :param formatting_info:
  60. The default is ``False``, which saves memory.
  61. In this case, "Blank" cells, which are those with their own formatting
  62. information but no data, are treated as empty by ignoring the file's
  63. ``BLANK`` and ``MULBLANK`` records.
  64. This cuts off any bottom or right "margin" of rows of empty or blank
  65. cells.
  66. Only :meth:`~xlrd.sheet.Sheet.cell_value` and
  67. :meth:`~xlrd.sheet.Sheet.cell_type` are available.
  68. When ``True``, formatting information will be read from the spreadsheet
  69. file. This provides all cells, including empty and blank cells.
  70. Formatting information is available for each cell.
  71. Note that this will raise a NotImplementedError when used with an
  72. xlsx file.
  73. :param on_demand:
  74. Governs whether sheets are all loaded initially or when demanded
  75. by the caller. See :doc:`on_demand`.
  76. :param ragged_rows:
  77. The default of ``False`` means all rows are padded out with empty cells so
  78. that all rows have the same size as found in
  79. :attr:`~xlrd.sheet.Sheet.ncols`.
  80. ``True`` means that there are no empty cells at the ends of rows.
  81. This can result in substantial memory savings if rows are of widely
  82. varying sizes. See also the :meth:`~xlrd.sheet.Sheet.row_len` method.
  83. :param ignore_workbook_corruption:
  84. This option allows to read corrupted workbooks.
  85. When ``False`` you may face CompDocError: Workbook corruption.
  86. When ``True`` that exception will be ignored.
  87. :returns: An instance of the :class:`~xlrd.book.Book` class.
  88. DATA
  89. FILE_FORMAT_DESCRIPTIONS = {'xls': 'Excel xls', 'xlsb': 'Excel 2007 xl...
  90. FMLA_TYPE_ARRAY = 4
  91. FMLA_TYPE_CELL = 1
  92. FMLA_TYPE_COND_FMT = 8
  93. FMLA_TYPE_DATA_VAL = 16
  94. FMLA_TYPE_NAME = 32
  95. FMLA_TYPE_SHARED = 2
  96. PEEK_SIZE = 8
  97. XLS_SIGNATURE = b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1'
  98. XL_CELL_BLANK = 6
  99. XL_CELL_BOOLEAN = 4
  100. XL_CELL_DATE = 3
  101. XL_CELL_EMPTY = 0
  102. XL_CELL_ERROR = 5
  103. XL_CELL_NUMBER = 2
  104. XL_CELL_TEXT = 1
  105. ZIP_SIGNATURE = b'PK\x03\x04'
  106. __VERSION__ = '2.0.1'
  107. biff_text_from_num = {0: '(not BIFF)', 20: '2.0', 21: '2.1', 30: '3', ...
  108. empty_cell = empty:''
  109. error_text_from_code = {0: '#NULL!', 7: '#DIV/0!', 15: '#VALUE!', 23: ...
  110. oBOOL = 3
  111. oERR = 4
  112. oNUM = 2
  113. oREF = -1
  114. oREL = -2
  115. oSTRG = 1
  116. oUNK = 0
  117. okind_dict = {-2: 'oREL', -1: 'oREF', 0: 'oUNK', 1: 'oSTRG', 2: 'oNUM'...
  118. VERSION
  119. 2.0.1
  120. FILE
  121. e:\python_workspace\pythonproject\lib\site-packages\xlrd\__init__.py
3、实战案例
3-144、判断工作表内是否有公式
略,xlrd库不支持此功能,需要借助其他库实现
3-145、判断某单元格区域是否为数组公式区域
略,xlrd库不支持此功能,需要借助其他库实现
3-146、判断工作表内是否有数组公式
略,xlrd库不支持此功能,需要借助其他库实现
3-147、判断单元格的计算公式是否引用了其他工作表数据
略,xlrd库不支持此功能,需要借助其他库实现
3-148、判断单元格的计算公式是否引用了其他工作簿数据
略,xlrd库不支持此功能,需要借助其他库实现
3-149、判断某单元格是否为合并单元格区域的一部分
  1. # 149、判断某单元格是否为合并单元格区域的一部分
  2. import xlrd
  3. # 打开 Excel 文件
  4. workbook = xlrd.open_workbook(r'E:\360Downloads\test.xls')
  5. # 选择工作表
  6. sheet = workbook.sheet_by_index(0) # 或者使用 sheet_by_name('test1')
  7. # 获取合并单元格区域列表
  8. merged_cells = sheet.merged_cells
  9. # 假设我们要检查的单元格是 (row_num, col_num)
  10. row_num = 1
  11. col_num = 2
  12. # 遍历所有合并单元格区域
  13. for (start_row, start_col), (end_row, end_col) in merged_cells:
  14. # 检查单元格是否在合并区域内
  15. if start_row <= row_num <= end_row and start_col <= col_num <= end_col:
  16. print(f"单元格 ({row_num},{col_num}) 是合并单元格区域的一部分。")
  17. break
  18. else:
  19. print(f"单元格 ({row_num},{col_num}) 不是合并单元格区域的一部分!")
3-150、获取单元格区域内的值
  1. # 150、获取单元格区域内的值,并使其矩阵化
  2. import xlrd
  3. # 打开Excel文件
  4. workbook = xlrd.open_workbook(r'E:\360Downloads\test.xls')
  5. # 选择要读取的工作表
  6. sheet = workbook.sheet_by_name('test1')
  7. # 定义要读取的单元格区域(例如A1到C3)
  8. start_row = 0
  9. end_row = 2
  10. start_col = 0
  11. end_col = 2
  12. # 读取单元格区域的值
  13. cell_values = []
  14. for row in range(start_row, end_row + 1):
  15. row_cells = []
  16. for col in range(start_col, end_col + 1):
  17. cell_value = sheet.cell_value(row, col)
  18. row_cells.append(cell_value)
  19. cell_values.append(row_cells)
  20. # 输出单元格区域的矩阵化值
  21. for row in cell_values:
  22. print(row)
3-151、获取单元格内的前缀字符
略,xlrd库不支持此功能,需要借助其他库实现
3-152、判断单元格内的数字是否为文本字符
  1. # 152、判断单元格内的数字是否为文本字符
  2. import xlrd
  3. # 打开 Excel 文件
  4. workbook = xlrd.open_workbook(r'E:\360Downloads\test.xls')
  5. # 选择工作表
  6. sheet = workbook.sheet_by_index(0) # 或使用 sheet_by_name('Sheet1')
  7. # 假设我们要检查的单元格是 A1
  8. cell_value = sheet.cell_value(0, 0) # 行索引从 0 开始,列索引也从 0 开始
  9. # 检查单元格值是否为字符串,并且只包含数字字符
  10. if isinstance(cell_value, str) and cell_value.isdigit():
  11. print("单元格 A1 中的数字是作为文本字符读取的。")
  12. else:
  13. print("单元格 A1 中的数字不是作为文本字符读取的!")
3-153、获取单元格的格式
  1. # 153、获取单元格的格式
  2. import xlrd
  3. # 打开 Excel 文件,设置 formatting_info 参数为 True
  4. workbook = xlrd.open_workbook(r'E:\360Downloads\test.xls', formatting_info=True)
  5. sheet = workbook.sheet_by_name('test1')
  6. # 选择要获取格式的单元格
  7. row_index = 0
  8. col_index = 0
  9. # 获取单元格对象
  10. cell = sheet.cell(row_index, col_index)
  11. # 获取格式索引
  12. xf_index = cell.xf_index
  13. # 获取格式对象
  14. xf = workbook.xf_list[xf_index]
  15. # 获取格式的属性
  16. font = workbook.font_list[xf.font_index]
  17. background = xf.background # 直接从 xf 获取背景对象
  18. alignment = xf.alignment # 直接从 xf 获取对齐方式对象
  19. # 打印格式信息
  20. print(f"字体颜色: {font.colour_index}")
  21. print(f"背景颜色: {background.pattern_colour_index}")
  22. print(f"水平对齐方式: {alignment.hor_align}")
  23. print(f"垂直对齐方式: {alignment.vert_align}")
3-154、获取单元格的字体(Font)对象
  1. # 154、获取单元格的字体(Font)对象
  2. import xlrd
  3. # 打开Excel文件
  4. workbook = xlrd.open_workbook(r'E:\360Downloads\test.xls', formatting_info=True)
  5. # 选择工作表
  6. sheet = workbook.sheet_by_index(0)
  7. # 获取特定单元格的内容
  8. cell = sheet.cell(0, 0) # 获取第一个单元格 (A1)
  9. # 获取单元格的格式索引
  10. xf_index = cell.xf_index # 获取格式索引
  11. cell_xf = workbook.xf_list[xf_index] # 从格式列表中获取格式对象
  12. # 获取字体信息
  13. font = workbook.font_list[cell_xf.font_index]
  14. # 输出字体信息
  15. print(f'字体名称: {font.name}')
  16. print(f'字体大小: {font.height / 20}') # 字体大小单位是twips,需除以20
  17. print(f'是否加粗: {font.bold}')
  18. print(f'是否斜体: {font.italic}')
  19. print(f'字体颜色: #{font.colour_index:02X}')
  20. # 输出:
  21. # 字体名称: 微软雅黑
  22. # 字体大小: 9.0
  23. # 是否加粗: 0
  24. # 是否斜体: 0
  25. # 字体颜色: #08
3-155、获取单元格的内部(Interior)对象
  1. # 155、获取单元格的内部(Interior)对象
  2. import xlrd
  3. # 打开现有的 Excel 文件
  4. workbook = xlrd.open_workbook(r'E:\360Downloads\test.xls', formatting_info=True)
  5. # 获取第一个工作表
  6. sheet = workbook.sheet_by_index(0)
  7. # 获取单元格内容
  8. cell_value = sheet.cell(0, 0).value
  9. print('单元格内容:', cell_value)
  10. # 获取单元格的字体颜色(仅限于 .xls 文件)
  11. cell_xf_index = sheet.cell_xf_index(0, 0)
  12. cell_xf = workbook.xf_list[cell_xf_index]
  13. font_index = cell_xf.font_index
  14. font = workbook.font_list[font_index]
  15. print('字体颜色:', font.colour_index)
3-156、获取单元格的边框(Borders)对象
  1. # 156、获取单元格的边框(Borders)对象
  2. import xlrd
  3. # 打开现有的 Excel 文件
  4. workbook = xlrd.open_workbook(r'E:\360Downloads\test.xls', formatting_info=True)
  5. # 获取第一个工作表
  6. sheet = workbook.sheet_by_index(0)
  7. # 获取单元格的 XF 索引
  8. cell_xf_index = sheet.cell_xf_index(0, 0)
  9. cell_xf = workbook.xf_list[cell_xf_index]
  10. # 获取单元格边框信息
  11. border = cell_xf.border
  12. print(f"左边框: {border.left_line_style}")
  13. print(f"右边框: {border.right_line_style}")
  14. print(f"上边框: {border.top_line_style}")
  15. print(f"下边框: {border.bottom_line_style}")
3-157、获取单元格边框线的状态
  1. # 157、获取单元格边框线的状态
  2. import xlrd
  3. # 打开现有的 Excel 文件
  4. workbook = xlrd.open_workbook(r'E:\360Downloads\test.xls', formatting_info=True)
  5. # 获取第一个工作表
  6. sheet = workbook.sheet_by_index(0)
  7. # 获取单元格的 XF 索引
  8. cell_xf_index = sheet.cell_xf_index(0, 0)
  9. cell_xf = workbook.xf_list[cell_xf_index]
  10. # 获取单元格边框信息
  11. border = cell_xf.border
  12. print(f"左边框: {border.left_line_style}")
  13. print(f"右边框: {border.right_line_style}")
  14. print(f"上边框: {border.top_line_style}")
  15. print(f"下边框: {border.bottom_line_style}")
3-158、获取单元格的样式(Style)对象
  1. # 158、获取单元格的样式(Style)对象
  2. import xlrd
  3. # 打开Excel工作簿
  4. workbook = xlrd.open_workbook(r'E:\360Downloads\test.xls', formatting_info=True)
  5. # 获取第一个工作表
  6. sheet = workbook.sheet_by_index(0)
  7. # 获取指定单元格,例如第一行第一列的单元格
  8. row, col = 0, 0
  9. cell = sheet.cell(row, col)
  10. # 获取该单元格的样式索引
  11. xf_index = cell.xf_index
  12. # 从工作簿中获取样式对象
  13. cell_style = workbook.xf_list[xf_index]
  14. # 获取单元格的字体样式
  15. font = workbook.font_list[cell_style.font_index]
  16. # 打印字体相关信息
  17. print('Font Name:', font.name)
  18. print('Bold:', font.bold)
  19. print('Italic:', font.italic)
  20. print('Underline:', font.underline_type)
  21. # 获取单元格的背景填充信息
  22. background = cell_style.background
  23. # 打印背景颜色信息
  24. print('Background Color:', background.pattern_colour_index)
  25. print('Foreground Color:', background.pattern_colour_index)
3-159、获取单元格的条件格式
略,xlrd库不支持此功能,需要借助其他库实现
3-160、获取单元格的输入规则(有效性设置)
略,xlrd库不支持此功能,需要借助其他库实现
3-161、获取单元格的超链接
略,xlrd库不支持此功能,需要借助其他库实现
3-162、获取单元格的批注信息
  1. # 162、获取单元格的批注信息
  2. import xlrd
  3. # 打开Excel工作簿
  4. workbook = xlrd.open_workbook(r'E:\360Downloads\test.xls', formatting_info=True)
  5. # 获取第一个工作表
  6. sheet = workbook.sheet_by_index(0)
  7. # 获取批注信息
  8. for row_idx in range(sheet.nrows):
  9. for col_idx in range(sheet.ncols):
  10. cell = sheet.cell(row_idx, col_idx)
  11. comment = sheet.cell_note_map.get((row_idx, col_idx))
  12. if comment:
  13. print(f"Cell ({row_idx}, {col_idx}) Comment: {comment.text}") # 输出:Cell (0, 0) Comment: Hello,Python!
3-163、获取单元格的大小(行高和列宽)
  1. # 163、获取单元格的大小(行高和列宽)
  2. import xlrd
  3. # 打开Excel文件
  4. workbook = xlrd.open_workbook(r'E:\360Downloads\test.xls', formatting_info=True) # xlrd 仅支持 .xls 文件格式
  5. # 选择工作表
  6. sheet = workbook.sheet_by_index(0)
  7. # 获取所有列宽
  8. column_widths = sheet.colinfo_map
  9. for col_index, col_info in column_widths.items():
  10. print(f"列 {col_index} 的宽度: {col_info.width / 256}")
  11. # 获取所有行高
  12. row_heights = sheet.rowinfo_map
  13. for row_index, row_info in row_heights.items():
  14. print(f"行 {row_index} 的高度: {row_info.height / 20}")
3-164、获取单元格的坐标
  1. # 164、获取单元格的坐标
  2. import xlrd
  3. # 打开Excel文件
  4. workbook = xlrd.open_workbook(r'E:\360Downloads\test.xls', formatting_info=True) # xlrd 仅支持 .xls 文件格式
  5. # 选择工作表
  6. sheet = workbook.sheet_by_index(0)
  7. # 获取工作表的行数和列数
  8. num_rows = sheet.nrows
  9. num_cols = sheet.ncols
  10. # 遍历每个单元格并打印其坐标和内容
  11. for row_idx in range(num_rows):
  12. for col_idx in range(num_cols):
  13. cell_value = sheet.cell_value(row_idx, col_idx)
  14. print(f"单元格({row_idx}, {col_idx})的内容是: {cell_value}")

五、推荐阅读

1、Python筑基之旅
2、Python函数之旅
3、Python算法之旅
4、Python魔法之旅
5、博客个人主页
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/959628
推荐阅读
相关标签
  

闽ICP备14008679号