1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #!/usr/bin/env python # -*- coding: utf-8 -*- import warnings warnings.filterwarnings( 'ignore' ) import openpyxl from openpyxl.cell import MergedCell import os import re def read_excel(FileName,SheetName,ColLength = None ,StartRowCol = ( 2 , 1 )): try : #读excel if not os.path.exists(FileName): print ( "[%s] 文件不存在" % (FileName)) return [] wb = openpyxl.load_workbook(filename = FileName, data_only = True ) ws = wb[SheetName] RowId = StartRowCol[ 0 ] StartCol = StartRowCol[ 1 ] ColLength = ColLength if ColLength else ws.max_column ColLength = StartCol - 1 + ColLength #MaxRow = int(RowEnd) if RowEnd and int(RowEnd)<ws.max_row else ws.max_row MaxRow = ws.max_row ExcelData = [] while MaxRow > = RowId: ColId = StartCol RowData = [] while ColId< = ColLength: cell = ws.cell(row = RowId,column = ColId) if isinstance (cell,MergedCell): #判断该单元格是否合并单元格 for merged_range in ws.merged_cell_ranges: # 循环查找该单元格所属的合并区域 if cell.coordinate in merged_range: # 获取合并区域左上角的单元格作为该单元格的值返回 cell = ws.cell(row = merged_range.min_row, column = merged_range.min_col) break value = str (cell.value) if str (cell.value)! = 'None' else '' RowData.append(value) ColId + = 1 if len ( set (RowData))< 2 and RowData[ 0 ] = = '': pass else : ExcelData.append(RowData) RowId + = 1 wb.close() print ( '读取 [%s]文件 [%s]表数据完成...' % (FileName,SheetName)) return ExcelData except Exception as e: print (e) return [] if __name__ = = '__main__' : read_excel( "test.xlsx" , 'Sheet1' ,ColLength = None ,StartRowCol = ( 2 , 1 )) |
分类:
python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统