博客
关于我
python3 读写Excel
阅读量:350 次
发布时间:2019-03-04

本文共 2118 字,大约阅读时间需要 7 分钟。

python3 读写Excel

说明

  • 2007版以前的Excel(xls结尾的),需要使用xlrd读,xlwt写。
  • 2007版以后的Excel(xlsx结尾的),需要使用openpyxl来读写。

pypi的地址:

openpyxl文档地址:

举个栗子

# -*- coding: utf-8 -*-# 读写2003 excelimport xlrdimport xlwt# 读写2007 excelimport openpyxldef write03Excel(path):    wb = xlwt.Workbook()    sheet = wb.add_sheet("2003测试表")    value = [["名称", "价格", "出版社", "语言"],             ["如何高效读懂一本书", "22.3", "机械工业出版社", "中文"],             ["暗时间", "32.4", "人民邮电出版社", "中文"],             ["拆掉思维里的墙", "26.7", "机械工业出版社", "中文"]]    for i in range(0, 4):        for j in range(0, len(value[i])):            sheet.write(i, j, value[i][j])    wb.save(path)    print("写入数据成功!")def read03Excel(path):    workbook = xlrd.open_workbook(path)    sheets = workbook.sheet_names()    worksheet = workbook.sheet_by_name(sheets[0])    for i in range(0, worksheet.nrows):        row = worksheet.row(i)        for j in range(0, worksheet.ncols):            print(worksheet.cell_value(i, j), "\t", end="")        print()def write07Excel(path):    wb = openpyxl.Workbook()    sheet = wb.active    sheet.title = '2007测试表'    value = [["名称", "价格", "出版社", "语言"],             ["如何高效读懂一本书", "22.3", "机械工业出版社", "中文"],             ["暗时间", "32.4", "人民邮电出版社", "中文"],             ["拆掉思维里的墙", "26.7", "机械工业出版社", "中文"]]    for i in range(0, 4):        for j in range(0, len(value[i])):            sheet.cell(row=i+1, column=j+1, value=str(value[i][j]))    wb.save(path)    print("写入数据成功!")def read07Excel(path):    wb = openpyxl.load_workbook(path)    sheet = wb.get_sheet_by_name('2007测试表')    for row in sheet.rows:        for cell in row:            print(cell.value, "\t", end="")        print()file_2003 = 'data/2003.xls'file_2007 = 'data/2007.xlsx'write03Excel(file_2003)read03Excel(file_2003)write07Excel(file_2007)read07Excel(file_2007)    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   53   54   55   56   57   58   59   60   61   62   63   64   65   66   67   68

一切尽在demo中。

输出结果

这里写图片描述

这里写图片描述

这里写图片描述

你可能感兴趣的文章
IDEA 热部署太热情不好(失去焦点就热部署)
查看>>
访问docker中的nginx容器部署
查看>>
Airtest自动化测试 Docs airtest.core.android package
查看>>
SVN Unable to connect to a repository at URL 的解决方案
查看>>
python绘制一份完美的中国地图
查看>>
准确率94%!Python 机器学习识别微博或推特机器人
查看>>
Python 元组Tuple 相对于数组List的优势
查看>>
Android基本知识
查看>>
在Java中,return null 是否安全, 为什么?
查看>>
命令模式【Command Pattern】
查看>>
如何将自己写的代码编进系统
查看>>
数据结构有哪些
查看>>
OSI 7 层网络模型
查看>>
Spring Bean 生命周期
查看>>
JDK 内置线程池
查看>>
JVM 参数默认值查询
查看>>
异常的继承结构
查看>>
SVN 和 Git 区别
查看>>
JDK 内置的多线程协作工具类的使用场景
查看>>
Java 源代码到运行的过程
查看>>