Python读取xlsx文件的所有Python库大全(附代码)

Written by

in

文章目录
  • xlsx_readers_complete.py – 完整版本,包含所有库的详细示例 simple_examples.py – 简化版本,只包含核心代码 requirements.txt – 所有依赖库列表 README.md – 本说明文档
  • xlrd版本问题:xlrd 2.0+ 不再支持xlsx格式,如需使用请安装1.2.0版本 xlwings依赖:需要安装Microsoft Excel应用程序 Rust库:calamine和fastexcel可能需要Rust编译环境 内存使用:大文件建议使用polars、dask等高性能库 兼容性:某些库在不同操作系统上的表现可能不同
  • 新手/通用项目:使用 pandas 纯Excel处理:使用 openpyxl 高性能需求:使用 polars 或 fastexcel 大数据处理:使用 dask 或 vaex 与Excel交互:使用 xlwings 多格式支持:使用 pyexcel
  • 库名 小文件(<1MB) 中文件(1-100MB) 大文件(>100MB) 内存使用 pandas ⭐⭐⭐⭐ ⭐⭐⭐ ⭐⭐ 中等 openpyxl ⭐⭐⭐ ⭐⭐ ⭐ 较高 polars ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ 低 fastexcel ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐ 低 xlrd ⭐⭐⭐ ⭐⭐ ⭐ 中等
  • 所有示例都假设xlsx文件包含以下数据: 姓名 年龄 城市 张三 25 北京 李四 30 上海 王五 35 广州 读取后的列表格式: [    ['姓名', '年龄', '城市'],  # 列名(如果包含)    ['张三', 25, '北京'],    ['李四', 30, '上海'],    ['王五', 35, '广州']]
  • “”” 所有可以读取xlsx文件的Python库大全 每个库都提供读取xlsx文件每一行为列表的代码示例 “”” # ============================================================================ # 1. pandas – 最流行的数据分析库 # ============================================================================ def read_xlsx_with_pandas(): “””使用pandas读取xlsx文件””” import pandas as pd # 读取xlsx文件 df = pd.read_excel(‘example.xlsx’) # 方法1: 转换为列表的列表 rows_as_lists = df.values.tolist() # 方法2: 包含列名的方式 rows_with_headers = [df.columns.tolist()] + df.values.tolist() # 方法3: 逐行读取 rows = [] for index, row in df.iterrows(): rows.append(row.tolist()) return rows_as_lists # ============================================================================ # 2. openpyxl – 专门处理Excel文件的库 # ============================================================================ def read_xlsx_with_openpyxl(): “””使用openpyxl读取xlsx文件””” from openpyxl import load_workbook # 加载工作簿 workbook = load_workbook(‘example.xlsx’) sheet = workbook.active # 或者 workbook[‘Sheet1’] # 读取所有行为列表 rows = [] for row in sheet.iter_rows(values_only=True): rows.append(list(row)) return rows # ============================================================================ # 3. xlrd – 传统的Excel读取库 # ============================================================================ def read_xlsx_with_xlrd(): “””使用xlrd读取xlsx文件””” import xlrd # 打开工作簿 workbook = xlrd.open_workbook(‘example.xlsx’) sheet = workbook.sheet_by_index(0) # 或者 workbook.sheet_by_name(‘Sheet1’) # 读取所有行 rows = [] for row_idx in range(sheet.nrows): row = [] for col_idx in range(sheet.ncols): row.append(sheet.cell_value(row_idx, col_idx)) rows.append(row) return rows # ============================================================================ # 4. xlwings – 与Excel应用程序交互的库 # ============================================================================ def read_xlsx_with_xlwings(): “””使用xlwings读取xlsx文件””” import xlwings as xw # 打开Excel应用程序和工作簿 app = xw.App(visible=False) workbook = app.books.open(‘example.xlsx’) sheet = workbook.sheets[0] # 获取使用区域的数据 used_range = sheet.used_range rows = used_range.value # 如果只有一行数据,确保返回列表的列表 if isinstance(rows[0], (int, float, str)): rows = [rows] # 关闭工作簿和应用程序 workbook.close() app.quit() return rows # ============================================================================ # 5. pyexcel – 统一的电子表格接口 # ============================================================================ def read_xlsx_with_pyexcel(): “””使用pyexcel读取xlsx文件””” import pyexcel # 直接读取为列表的列表 rows = pyexcel.get_records(file_name=’example.xlsx’) # 转换为纯列表格式 if rows: # 获取列名 headers = list(rows[0].keys()) result = [headers] # 添加数据行 for record in rows: result.append([record[header] for header in headers]) return result return [] # ============================================================================ # 6. xlsxwriter + openpyxl 组合 (xlsxwriter主要用于写入,这里用openpyxl读取) # ============================================================================ def read_xlsx_with_xlsxwriter_openpyxl(): “””xlsxwriter主要用于写入,读取仍使用openpyxl””” # xlsxwriter主要用于创建xlsx文件,读取功能有限 # 通常与openpyxl结合使用 return read_xlsx_with_openpyxl() # ============================================================================ # 7. python-excel – 另一个Excel处理库 # ============================================================================ def read_xlsx_with_python_excel(): “””使用python-excel读取xlsx文件””” # 注意:python-excel通常指的是xlrd/xlwt/xlutils的组合 # 对于xlsx文件,推荐使用xlrd return read_xlsx_with_xlrd() # ============================================================================ # 8. tablib – 表格数据处理库 # ============================================================================ def read_xlsx_with_tablib(): “””使用tablib读取xlsx文件””” import tablib # 读取xlsx文件 with open(‘example.xlsx’, ‘rb’) as f: dataset = tablib.Dataset().load(f, format=’xlsx’) # 转换为列表的列表 rows = [] if dataset.headers: rows.append(dataset.headers) for row in dataset: rows.append(list(row)) return rows # ============================================================================ # 9. xlutils – Excel工具集合 # ============================================================================ def read_xlsx_with_xlutils(): “””使用xlutils读取xlsx文件””” # xlutils主要用于xls文件,对xlsx支持有限 # 建议使用openpyxl或pandas return read_xlsx_with_openpyxl() # ============================================================================ # 10. ezodf – OpenDocument格式库(也支持xlsx) # ============================================================================ def read_xlsx_with_ezodf(): “””使用ezodf读取xlsx文件””” # ezodf主要用于ODF格式,对xlsx支持有限 # 建议使用专门的xlsx库 return read_xlsx_with_openpyxl() # ============================================================================ # 11. pyexcel-xlsx – pyexcel的xlsx插件 # ============================================================================ def read_xlsx_with_pyexcel_xlsx(): “””使用pyexcel-xlsx读取xlsx文件””” import pyexcel_xlsx import pyexcel # 读取xlsx文件 sheet = pyexcel.get_sheet(file_name=’example.xlsx’) # 转换为列表的列表 rows = [] for row in sheet: rows.append(list(row)) return rows # ============================================================================ # 12. xlrd3 – xlrd的Python 3版本 # ============================================================================ def read_xlsx_with_xlrd3(): “””使用xlrd3读取xlsx文件””” # xlrd3是xlrd的分支,用法基本相同 return read_xlsx_with_xlrd() # ============================================================================ # 13. calamine-python – Rust calamine的Python绑定 # ============================================================================ def read_xlsx_with_calamine(): “””使用calamine读取xlsx文件””” try: from calamine import CalamineWorkbook # 打开工作簿 workbook = CalamineWorkbook.from_path(‘example.xlsx’) # 读取第一个工作表 sheet_names = workbook.sheet_names if sheet_names: sheet = workbook.get_sheet_by_name(sheet_names[0]) rows = [] for row in sheet.iter_rows(): rows.append(list(row)) return rows except ImportError: print(“calamine库未安装,使用openpyxl替代”) return read_xlsx_with_openpyxl() # ============================================================================ # 14. fastexcel – 快速Excel读取库 # ============================================================================ def read_xlsx_with_fastexcel(): “””使用fastexcel读取xlsx文件””” try: import fastexcel # 读取Excel文件 df = fastexcel.read_excel(‘example.xlsx’) # 转换为列表的列表 rows = df.values.tolist() # 添加列名作为第一行 if hasattr(df, ‘columns’): rows.insert(0, df.columns.tolist()) return rows except ImportError: print(“fastexcel库未安装,使用pandas替代”) return read_xlsx_with_pandas() # ============================================================================ # 15. polars – 高性能数据处理库 # ============================================================================ def read_xlsx_with_polars(): “””使用polars读取xlsx文件””” try: import polars as pl # 读取xlsx文件 df = pl.read_excel(‘example.xlsx’) # 转换为列表的列表 rows = df.to_numpy().tolist() # 添加列名作为第一行 rows.insert(0, df.columns) return rows except ImportError: print(“polars库未安装,使用pandas替代”) return read_xlsx_with_pandas() # ============================================================================ # 16. dask – 并行计算库 # ============================================================================ def read_xlsx_with_dask(): “””使用dask读取xlsx文件””” try: import dask.dataframe as dd # dask不直接支持xlsx,需要先用pandas读取 import pandas as pd df = pd.read_excel(‘example.xlsx’) # 转换为dask dataframe ddf = dd.from_pandas(df, npartitions=1) # 计算并转换为列表 rows = ddf.compute().values.tolist() return rows except ImportError: print(“dask库未安装,使用pandas替代”) return read_xlsx_with_pandas() # ============================================================================ # 17. modin – 加速pandas的库 # ============================================================================ def read_xlsx_with_modin(): “””使用modin读取xlsx文件””” try: import modin.pandas as pd # 读取xlsx文件 df = pd.read_excel(‘example.xlsx’) # 转换为列表的列表 rows = df.values.tolist() return rows except ImportError: print(“modin库未安装,使用pandas替代”) return read_xlsx_with_pandas() # ============================================================================ # 18. vaex – 大数据处理库 # ============================================================================ def read_xlsx_with_vaex(): “””使用vaex读取xlsx文件””” try: import vaex import pandas as pd # vaex不直接支持xlsx,需要先用pandas读取 df_pandas = pd.read_excel(‘example.xlsx’) # 转换为vaex dataframe df_vaex = vaex.from_pandas(df_pandas) # 转换为列表的列表 rows = df_vaex.to_pandas_df().values.tolist() return rows except ImportError: print(“vaex库未安装,使用pandas替代”) return read_xlsx_with_pandas() # ============================================================================ # 使用示例和测试函数 # ============================================================================ def create_sample_xlsx(): “””创建示例xlsx文件用于测试””” import pandas as pd # 创建示例数据 data = { ‘姓名’: [‘张三’, ‘李四’, ‘王五’], ‘年龄’: [25, 30, 35], ‘城市’: [‘北京’, ‘上海’, ‘广州’] } df = pd.DataFrame(data) df.to_excel(‘example.xlsx’, index=False) print(“已创建示例文件 example.xlsx”) def test_all_readers(): “””测试所有读取方法””” # 创建示例文件 create_sample_xlsx() readers = [ (“pandas”, read_xlsx_with_pandas), (“openpyxl”, read_xlsx_with_openpyxl), (“xlrd”, read_xlsx_with_xlrd), (“pyexcel”, read_xlsx_with_pyexcel), (“tablib”, read_xlsx_with_tablib), (“pyexcel-xlsx”, read_xlsx_with_pyexcel_xlsx), (“calamine”, read_xlsx_with_calamine), (“fastexcel”, read_xlsx_with_fastexcel), (“polars”, read_xlsx_with_polars), (“dask”, read_xlsx_with_dask), (“modin”, read_xlsx_with_modin), (“vaex”, read_xlsx_with_vaex), ] for name, reader_func in readers: try: print(f”n=== 使用 {name} 读取 ===”) rows = reader_func() for i, row in enumerate(rows): print(f”第{i+1}行: {row}”) except Exception as e: print(f”{name} 读取失败: {e}”) if __name__ == “__main__”: # 运行测试 test_all_readers() 到此这篇关于Python读取xlsx文件的所有Python库大全(附代码)的文章就介绍到这了,更多相关Python读取xlsx内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 您可能感兴趣的文章: python中如何读取xlsx文件 python使用pandas读取json文件并进行刷选导出xlsx文件的方法示例 如何使用Python读取.xlsx指定行列 用python实现读取xlsx表格操作 python操作xlsx格式文件并读取 用python读取xlsx文件 Python读取xlsx文件的实现方法 python读取xlsx的方法
  • 目录
    • 文件说明
    • 库分类和推荐
      • 最推荐的库
      • 专业库
      • 高性能库
      • 传统库
    • 快速开始
      • 最简单的方法(推荐)
      • 不依赖pandas的方法
      • 自动选择库的方法
    • 安装依赖
      • 最小安装(适合大多数场景)
      • 完整安装(所有库)
      • 按需安装
    •  注意事项
      • 选择建议
        • 性能对比
          • 示例数据格式
            • 完整代码

              xlsx_readers_complete.py – 完整版本,包含所有库的详细示例

              simple_examples.py – 简化版本,只包含核心代码

              requirements.txt – 所有依赖库列表

              README.md – 本说明文档

              库名 特点 适用场景
              pandas 功能最强大,生态最完善 数据分析、数据科学项目
              openpyxl 专门处理Excel,功能全面 纯Excel文件处理
              polars 高性能,内存效率高 大数据处理

              库名 特点 适用场景
              xlwings 与Excel应用程序交互 需要Excel高级功能
              pyexcel 统一接口,支持多种格式 多格式文件处理
              tablib 数据导入导出 数据转换和导出

              库名 特点 适用场景
              fastexcel 基于Rust,速度快 大文件快速读取
              calamine Rust实现,高性能 性能要求极高的场景
              dask 并行计算 超大文件处理
              modin 加速pandas pandas性能优化
              vaex 大数据可视化 亿级数据处理

              库名 特点 适用场景
              xlrd 传统Excel读取库 老项目维护(注意版本兼容性)
              xlutils Excel工具集 配合xlrd使用

              import pandas as pd
              
              # 读取xlsx文件每一行为列表
              df = pd.read_excel('your_file.xlsx')
              rows = df.values.tolist()  # 不包含列名
              # 或者包含列名:
              rows_with_headers = [df.columns.tolist()] + df.values.tolist()
              

              from openpyxl import load_workbook
              
              workbook = load_workbook('your_file.xlsx')
              sheet = workbook.active
              rows = [list(row) for row in sheet.iter_rows(values_only=True)]
              

              def read_xlsx_auto(filename):
                  """自动选择可用的库来读取xlsx文件"""
                  try:
                      import pandas as pd
                      df = pd.read_excel(filename)
                      return [df.columns.tolist()] + df.values.tolist()
                  except ImportError:
                      from openpyxl import load_workbook
                      workbook = load_workbook(filename)
                      sheet = workbook.active
                      return [list(row) for row in sheet.iter_rows(values_only=True)]
              

              pip install pandas openpyxl
              

              pip install -r requirements.txt
              

              数据分析场景:

              pip install pandas openpyxl xlwings
              

              高性能场景:

              pip install polars fastexcel
              

              大数据场景:

              pip install dask[complete] modin[all] vaex
              

              • xlrd版本问题:xlrd 2.0+ 不再支持xlsx格式,如需使用请安装1.2.0版本
              • xlwings依赖:需要安装Microsoft Excel应用程序
              • Rust库:calamine和fastexcel可能需要Rust编译环境
              • 内存使用:大文件建议使用polars、dask等高性能库
              • 兼容性:某些库在不同操作系统上的表现可能不同

              新手/通用项目:使用 pandas

              纯Excel处理:使用 openpyxl

              高性能需求:使用 polarsfastexcel

              大数据处理:使用 daskvaex

              与Excel交互:使用 xlwings

              多格式支持:使用 pyexcel

              库名 小文件(<1MB) 中文件(1-100MB) 大文件(>100MB) 内存使用
              pandas ⭐⭐⭐⭐ ⭐⭐⭐ ⭐⭐ 中等
              openpyxl ⭐⭐⭐ ⭐⭐ 较高
              polars ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐
              fastexcel ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐
              xlrd ⭐⭐⭐ ⭐⭐ 中等

              所有示例都假设xlsx文件包含以下数据:

              姓名 年龄 城市
              张三 25 北京
              李四 30 上海
              王五 35 广州

              读取后的列表格式:

              [
                  ['姓名', '年龄', '城市'],  # 列名(如果包含)
                  ['张三', 25, '北京'],
                  ['李四', 30, '上海'],
                  ['王五', 35, '广州']
              ]

              """
              所有可以读取xlsx文件的Python库大全
              每个库都提供读取xlsx文件每一行为列表的代码示例
              """
              
              # ============================================================================
              # 1. pandas - 最流行的数据分析库
              # ============================================================================
              def read_xlsx_with_pandas():
                  """使用pandas读取xlsx文件"""
                  import pandas as pd
                  
                  # 读取xlsx文件
                  df = pd.read_excel('example.xlsx')
                  
                  # 方法1: 转换为列表的列表
                  rows_as_lists = df.values.tolist()
                  
                  # 方法2: 包含列名的方式
                  rows_with_headers = [df.columns.tolist()] + df.values.tolist()
                  
                  # 方法3: 逐行读取
                  rows = []
                  for index, row in df.iterrows():
                      rows.append(row.tolist())
                  
                  return rows_as_lists
              
              # ============================================================================
              # 2. openpyxl - 专门处理Excel文件的库
              # ============================================================================
              def read_xlsx_with_openpyxl():
                  """使用openpyxl读取xlsx文件"""
                  from openpyxl import load_workbook
                  
                  # 加载工作簿
                  workbook = load_workbook('example.xlsx')
                  sheet = workbook.active  # 或者 workbook['Sheet1']
                  
                  # 读取所有行为列表
                  rows = []
                  for row in sheet.iter_rows(values_only=True):
                      rows.append(list(row))
                  
                  return rows
              
              # ============================================================================
              # 3. xlrd - 传统的Excel读取库
              # ============================================================================
              def read_xlsx_with_xlrd():
                  """使用xlrd读取xlsx文件"""
                  import xlrd
                  
                  # 打开工作簿
                  workbook = xlrd.open_workbook('example.xlsx')
                  sheet = workbook.sheet_by_index(0)  # 或者 workbook.sheet_by_name('Sheet1')
                  
                  # 读取所有行
                  rows = []
                  for row_idx in range(sheet.nrows):
                      row = []
                      for col_idx in range(sheet.ncols):
                          row.append(sheet.cell_value(row_idx, col_idx))
                      rows.append(row)
                  
                  return rows
              
              # ============================================================================
              # 4. xlwings - 与Excel应用程序交互的库
              # ============================================================================
              def read_xlsx_with_xlwings():
                  """使用xlwings读取xlsx文件"""
                  import xlwings as xw
                  
                  # 打开Excel应用程序和工作簿
                  app = xw.App(visible=False)
                  workbook = app.books.open('example.xlsx')
                  sheet = workbook.sheets[0]
                  
                  # 获取使用区域的数据
                  used_range = sheet.used_range
                  rows = used_range.value
                  
                  # 如果只有一行数据,确保返回列表的列表
                  if isinstance(rows[0], (int, float, str)):
                      rows = [rows]
                  
                  # 关闭工作簿和应用程序
                  workbook.close()
                  app.quit()
                  
                  return rows
              
              # ============================================================================
              # 5. pyexcel - 统一的电子表格接口
              # ============================================================================
              def read_xlsx_with_pyexcel():
                  """使用pyexcel读取xlsx文件"""
                  import pyexcel
                  
                  # 直接读取为列表的列表
                  rows = pyexcel.get_records(file_name='example.xlsx')
                  
                  # 转换为纯列表格式
                  if rows:
                      # 获取列名
                      headers = list(rows[0].keys())
                      result = [headers]
                      
                      # 添加数据行
                      for record in rows:
                          result.append([record[header] for header in headers])
                      
                      return result
                  
                  return []
              
              # ============================================================================
              # 6. xlsxwriter + openpyxl 组合 (xlsxwriter主要用于写入,这里用openpyxl读取)
              # ============================================================================
              def read_xlsx_with_xlsxwriter_openpyxl():
                  """xlsxwriter主要用于写入,读取仍使用openpyxl"""
                  # xlsxwriter主要用于创建xlsx文件,读取功能有限
                  # 通常与openpyxl结合使用
                  return read_xlsx_with_openpyxl()
              
              # ============================================================================
              # 7. python-excel - 另一个Excel处理库
              # ============================================================================
              def read_xlsx_with_python_excel():
                  """使用python-excel读取xlsx文件"""
                  # 注意:python-excel通常指的是xlrd/xlwt/xlutils的组合
                  # 对于xlsx文件,推荐使用xlrd
                  return read_xlsx_with_xlrd()
              
              # ============================================================================
              # 8. tablib - 表格数据处理库
              # ============================================================================
              def read_xlsx_with_tablib():
                  """使用tablib读取xlsx文件"""
                  import tablib
                  
                  # 读取xlsx文件
                  with open('example.xlsx', 'rb') as f:
                      dataset = tablib.Dataset().load(f, format='xlsx')
                  
                  # 转换为列表的列表
                  rows = []
                  if dataset.headers:
                      rows.append(dataset.headers)
                  
                  for row in dataset:
                      rows.append(list(row))
                  
                  return rows
              
              # ============================================================================
              # 9. xlutils - Excel工具集合
              # ============================================================================
              def read_xlsx_with_xlutils():
                  """使用xlutils读取xlsx文件"""
                  # xlutils主要用于xls文件,对xlsx支持有限
                  # 建议使用openpyxl或pandas
                  return read_xlsx_with_openpyxl()
              
              # ============================================================================
              # 10. ezodf - OpenDocument格式库(也支持xlsx)
              # ============================================================================
              def read_xlsx_with_ezodf():
                  """使用ezodf读取xlsx文件"""
                  # ezodf主要用于ODF格式,对xlsx支持有限
                  # 建议使用专门的xlsx库
                  return read_xlsx_with_openpyxl()
              
              # ============================================================================
              # 11. pyexcel-xlsx - pyexcel的xlsx插件
              # ============================================================================
              def read_xlsx_with_pyexcel_xlsx():
                  """使用pyexcel-xlsx读取xlsx文件"""
                  import pyexcel_xlsx
                  import pyexcel
                  
                  # 读取xlsx文件
                  sheet = pyexcel.get_sheet(file_name='example.xlsx')
                  
                  # 转换为列表的列表
                  rows = []
                  for row in sheet:
                      rows.append(list(row))
                  
                  return rows
              
              # ============================================================================
              # 12. xlrd3 - xlrd的Python 3版本
              # ============================================================================
              def read_xlsx_with_xlrd3():
                  """使用xlrd3读取xlsx文件"""
                  # xlrd3是xlrd的分支,用法基本相同
                  return read_xlsx_with_xlrd()
              
              # ============================================================================
              # 13. calamine-python - Rust calamine的Python绑定
              # ============================================================================
              def read_xlsx_with_calamine():
                  """使用calamine读取xlsx文件"""
                  try:
                      from calamine import CalamineWorkbook
                      
                      # 打开工作簿
                      workbook = CalamineWorkbook.from_path('example.xlsx')
                      
                      # 读取第一个工作表
                      sheet_names = workbook.sheet_names
                      if sheet_names:
                          sheet = workbook.get_sheet_by_name(sheet_names[0])
                          rows = []
                          for row in sheet.iter_rows():
                              rows.append(list(row))
                          return rows
                  except ImportError:
                      print("calamine库未安装,使用openpyxl替代")
                      return read_xlsx_with_openpyxl()
              
              # ============================================================================
              # 14. fastexcel - 快速Excel读取库
              # ============================================================================
              def read_xlsx_with_fastexcel():
                  """使用fastexcel读取xlsx文件"""
                  try:
                      import fastexcel
                      
                      # 读取Excel文件
                      df = fastexcel.read_excel('example.xlsx')
                      
                      # 转换为列表的列表
                      rows = df.values.tolist()
                      
                      # 添加列名作为第一行
                      if hasattr(df, 'columns'):
                          rows.insert(0, df.columns.tolist())
                      
                      return rows
                  except ImportError:
                      print("fastexcel库未安装,使用pandas替代")
                      return read_xlsx_with_pandas()
              
              # ============================================================================
              # 15. polars - 高性能数据处理库
              # ============================================================================
              def read_xlsx_with_polars():
                  """使用polars读取xlsx文件"""
                  try:
                      import polars as pl
                      
                      # 读取xlsx文件
                      df = pl.read_excel('example.xlsx')
                      
                      # 转换为列表的列表
                      rows = df.to_numpy().tolist()
                      
                      # 添加列名作为第一行
                      rows.insert(0, df.columns)
                      
                      return rows
                  except ImportError:
                      print("polars库未安装,使用pandas替代")
                      return read_xlsx_with_pandas()
              
              # ============================================================================
              # 16. dask - 并行计算库
              # ============================================================================
              def read_xlsx_with_dask():
                  """使用dask读取xlsx文件"""
                  try:
                      import dask.dataframe as dd
                      
                      # dask不直接支持xlsx,需要先用pandas读取
                      import pandas as pd
                      df = pd.read_excel('example.xlsx')
                      
                      # 转换为dask dataframe
                      ddf = dd.from_pandas(df, npartitions=1)
                      
                      # 计算并转换为列表
                      rows = ddf.compute().values.tolist()
                      
                      return rows
                  except ImportError:
                      print("dask库未安装,使用pandas替代")
                      return read_xlsx_with_pandas()
              
              # ============================================================================
              # 17. modin - 加速pandas的库
              # ============================================================================
              def read_xlsx_with_modin():
                  """使用modin读取xlsx文件"""
                  try:
                      import modin.pandas as pd
                      
                      # 读取xlsx文件
                      df = pd.read_excel('example.xlsx')
                      
                      # 转换为列表的列表
                      rows = df.values.tolist()
                      
                      return rows
                  except ImportError:
                      print("modin库未安装,使用pandas替代")
                      return read_xlsx_with_pandas()
              
              # ============================================================================
              # 18. vaex - 大数据处理库
              # ============================================================================
              def read_xlsx_with_vaex():
                  """使用vaex读取xlsx文件"""
                  try:
                      import vaex
                      import pandas as pd
                      
                      # vaex不直接支持xlsx,需要先用pandas读取
                      df_pandas = pd.read_excel('example.xlsx')
                      
                      # 转换为vaex dataframe
                      df_vaex = vaex.from_pandas(df_pandas)
                      
                      # 转换为列表的列表
                      rows = df_vaex.to_pandas_df().values.tolist()
                      
                      return rows
                  except ImportError:
                      print("vaex库未安装,使用pandas替代")
                      return read_xlsx_with_pandas()
              
              # ============================================================================
              # 使用示例和测试函数
              # ============================================================================
              def create_sample_xlsx():
                  """创建示例xlsx文件用于测试"""
                  import pandas as pd
                  
                  # 创建示例数据
                  data = {
                      '姓名': ['张三', '李四', '王五'],
                      '年龄': [25, 30, 35],
                      '城市': ['北京', '上海', '广州']
                  }
                  
                  df = pd.DataFrame(data)
                  df.to_excel('example.xlsx', index=False)
                  print("已创建示例文件 example.xlsx")
              
              def test_all_readers():
                  """测试所有读取方法"""
                  # 创建示例文件
                  create_sample_xlsx()
                  
                  readers = [
                      ("pandas", read_xlsx_with_pandas),
                      ("openpyxl", read_xlsx_with_openpyxl),
                      ("xlrd", read_xlsx_with_xlrd),
                      ("pyexcel", read_xlsx_with_pyexcel),
                      ("tablib", read_xlsx_with_tablib),
                      ("pyexcel-xlsx", read_xlsx_with_pyexcel_xlsx),
                      ("calamine", read_xlsx_with_calamine),
                      ("fastexcel", read_xlsx_with_fastexcel),
                      ("polars", read_xlsx_with_polars),
                      ("dask", read_xlsx_with_dask),
                      ("modin", read_xlsx_with_modin),
                      ("vaex", read_xlsx_with_vaex),
                  ]
                  
                  for name, reader_func in readers:
                      try:
                          print(f"n=== 使用 {name} 读取 ===")
                          rows = reader_func()
                          for i, row in enumerate(rows):
                              print(f"第{i+1}行: {row}")
                      except Exception as e:
                          print(f"{name} 读取失败: {e}")
              
              if __name__ == "__main__":
                  # 运行测试
                  test_all_readers()
              

              到此这篇关于Python读取xlsx文件的所有Python库大全(附代码)的文章就介绍到这了,更多相关Python读取xlsx内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

              您可能感兴趣的文章:

              • python中如何读取xlsx文件
              • python使用pandas读取json文件并进行刷选导出xlsx文件的方法示例
              • 如何使用Python读取.xlsx指定行列
              • 用python实现读取xlsx表格操作
              • python操作xlsx格式文件并读取
              • 用python读取xlsx文件
              • Python读取xlsx文件的实现方法
              • python读取xlsx的方法

              站内搜索