xlrd 模块
xlrd 是 python 中一个第三方的用于读取 excle 表格的模块, 很多企业在没有使用计算机管理前大多使用表格来管理数据, 所以导入表格还是非常常用的!
安装 xlrd
pip install xlrd
exlce 结构分析
一个 excle 表格包含多个 sheet
一个 sheet 中包含多行多列
每个单元格具备唯一的行号和列号
常用函数
- import xlrd
- # 读取文件
- work_book = xlrd.open_workbook("/Users/jerry/Desktop / 公司机密数据. xlsx")
- # 选取一个表
- # 获取所有所有表格名称
- print(work_book.sheet_names())
- # 选择第 2 个 索引从 0 开始
- sheet = work_book.sheet_by_index(1)
- # 表格名称
- print(sheet.name)
- # 行数
- print(sheet.nrows)
- # 列数
- print(sheet.ncols)
- # 批量读取行数据
- # 取出第 6 行的全部内容包含数据类型
- print(sheet.row(6))
- # 取出第 6 行的内容包含数据类型 从第 3 列开始获取
- print(sheet.row_slice(6,start_colx=3))
- # 取出第 6 行的内容包含数据类型 从第 3 列开始获取
- print(sheet.row_slice(6,start_colx=4,end_colx=5))
- # 获取该行所有数据类型 一数字表示
- # print(sheet.row_types(6))
- # print(sheet.row_values(6))
- # 单元格的处理
- print(sheet.cell(0,0).value) # 取值
- print(sheet.cell(0,0).ctype) # 取类型
- print(sheet.cell_value(2,0)) # 直接取值
- print(sheet.row(0)[0]) # 先取行再取单元格
- print(sheet.col(0)) # 第 0 列所有数据
- print(sheet.col(0)) # 先取列再取单元格
- print(sheet.cell_type(0,0))
- # 单元格位置转换
- print(xlrd.cellname(2,1))
- print(xlrd.cellnameabs(0,2))
- print(xlrd.colname(5))
- # 时间类型转换
- # print(sheet.cell(6,5).value)
- # print(xlrd.xldate_as_datetime(sheet.cell(6,5).value,1))
案例:
读取一个报价单 其第二个 sheet 包含合并单元格
文件地址: https://share.weiyun.com/5GaLY2m
- import xlrd
- sheet = xlrd.open_workbook("报价单. xlsx").sheet_by_index(1)
- def get_text(row,col):
- # 判断该坐标是否是被合并的单元格 合并单元格的数据都在合并区域的第一个位置
- for ces in sheet.merged_cells:
- if (row>= ces[0] and row <ces[1]) and (col>= ces[2] and col < ces[3]):
- return sheet.cell(ces[0],ces[2]).value # 取出合并区域的第一个数据
- return sheet.cell(row,col).value #正常取出对应数据
- keys = sheet.row_values(1) # 获取所有的列标题
- data = []
- for row in range(2,sheet.nrows):
- dic = {}
- for col in range(sheet.ncols):
- k = keys[col] #确定 key
- res = get_text(row,col)
- dic[k] = res # 确定值 并存储
- data.append(dic)
- print(data)
- # 序列化为 JSON
- import JSON
- JSON.dump(data,open("test.json","wt"),ensure_ascii=False)
xlwt 模块
是 python 中一个第三方的用于写入 excle 数据到表格的模块
用代码来编写 exlce 是非常低效的 所以该模块了解即可.
- import xlwt
- # 创建工作簿
- work = xlwt.Workbook()
- # 创建一个表
- sheet = work.add_sheet("员工信息数据")
- # 创建一个字体对象
- font = xlwt.Font()
- font.name = "Times New Roman" # 字体名称
- font.bold = True # 加粗
- font.italic = True # 斜体
- font.underline = True # 下划线
- # 创建一个样式对象
- style = xlwt.XFStyle()
- style.font = font
- # 写入标题
- for k in keys:
- sheet.write(0,keys.index(k),k,style)
- # 写入数据
- for i in infos:
- for k in keys:
- sheet.write(1 + infos.index(i),keys.index(k),label = i[k])
- # 保存至文件
- work.save("test.xls")
面试题:
- import xlrd
- import pymysql
- # 读取文件
- work_book = xlrd.open_workbook("/xxx/xxx.xlsx")
- # 选取一个表
- sheet = work_book.sheet_by_index(0)
- # 遍历表格数据
- datas = []
- for row in range(1,sheet.nrows):
- temp_list =[]
- for col in range(sheet.ncols):
- value = sheet.cell_value(row,col)
- temp_list.append(value)
- datas.append(temp_list)
- # 打开数据库连接
- db = pymysql.connect(host='localhost', port=3306,
- user='username', passwd='password', db='database_name', charset='utf8')
- # 使用 cursor() 方法获取操作游标
- cursor = db.cursor()
- # SQL 插入语句
- sql = "INSERT INTO SHOP(shop_code, shop_name, month) VALUES (%s,%s,%s)"
- try:
- # 执行 sql 语句
- cursor.executemany(sql, datas)
- # 提交到数据库执行
- db.commit()
- except :
- # 如果发生错误则回滚
- db.rollback()
- # 关闭游标
- cursor.close()
- # 关闭数据库连接
- db.close()
来源: https://www.cnblogs.com/yangyuanhu/p/11101372.html