Python (二) 读写excel文件


程序员的公众号:源1024获取更多资料,无加密无套路!

最近整理了一波电子书籍资料,包含《Effective Java中文版 第2版》《深入JAVA虚拟机》,《重构改善既有代码设计》,《MySQL高性能-第3版》,《Java并发编程实战》等等
获取方式: 关注公众号并回复 电子书 领取,更多内容持续奉上


安装第三方库

pip install xlrd

pip install openpyxl

from openpyxl import load_workbook

# # 默认打开的文件为可读写,若有需要可以指定参数read_only为True
path = 'output.xlsx'
wb = load_workbook(path,read_only=True)
sheet = wb.active
# 打印总行数
print(sheet.max_row)
# ptint总列数
print(sheet.max_column)

# 循环将打印所有列的名称
max_col = sheet.max_column
for i in range(1, max_col + 1):
    cell = sheet.cell(row = 1, column = i)
    print(cell.value)

m_row = sheet.max_row
# 循环将打印前两列的值
for i in range(1, m_row + 1):
    cell = sheet.cell(row = i, column = 1)
    cell2 = sheet.cell(row = i, column = 2)
    print(cell.value,cell2.value)

将mysql查询的数据写入excel文件

import openpyxl
import pymysql

#创建工作簿对象
workbook = openpyxl.Workbook()
# 获得工作表
sheet = workbook.active
# 添加工作表的标题
sheet.title = '测试导出excel文件'
#添加表头
sheet.append(('列1','列2','列3'))

#创建连接
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    passwd='1234',
    database='ry',
    charset='utf8mb4'
)

try:
    with conn.cursor() as cursor:
        cursor.execute(
            'select `dict_type`,`dict_name`,`status` from sys_dict_type'
        )
        # while循环实现了逐行抓取查询结果
        row = cursor.fetchone()
        while row:
             # 将数据逐行写入工作表中
            sheet.append(row)
            row = cursor.fetchone()
        #保存excel    
        workbook.save('output.xlsx')   
except pymysql.MySQLError as err:
    print(type(err),err)

finally:
    conn.close()                

效果:


系列文章索引

Python(一)关键字、内置函数

Python(二)基本数据类型

Python(三)数据类型转换

Python(四)字符串

Python(五)数字

Python(六) 列表

Python(七) 条件控制、循环语句

Python(八) 字典

Python(九) 集合

Python (十) 元组


相关推荐

  1. Qt Excel文件

    2023-12-06 21:38:02       20 阅读
  2. python文件

    2023-12-06 21:38:02       20 阅读
  3. Python文件

    2023-12-06 21:38:02       15 阅读
  4. 【C#】C#Excel文件

    2023-12-06 21:38:02       9 阅读
  5. python-文本数据

    2023-12-06 21:38:02       13 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-06 21:38:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-06 21:38:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-06 21:38:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-06 21:38:02       20 阅读

热门阅读

  1. docker安装mysql8

    2023-12-06 21:38:02       31 阅读
  2. 数据在内存中的存储

    2023-12-06 21:38:02       36 阅读
  3. linux下的抓包实现

    2023-12-06 21:38:02       39 阅读
  4. heatmap.js热力图【vue3】

    2023-12-06 21:38:02       30 阅读
  5. Linux定时器

    2023-12-06 21:38:02       32 阅读
  6. Android-P CameraSerivce

    2023-12-06 21:38:02       35 阅读
  7. 代币化对网约车区块链平台的影响

    2023-12-06 21:38:02       25 阅读
  8. Spring中的AOP思想

    2023-12-06 21:38:02       31 阅读
  9. 【重点】【区间问题】56.合并区间

    2023-12-06 21:38:02       38 阅读
  10. windows 服务的安装、启动、状态查询 c++实现

    2023-12-06 21:38:02       30 阅读