新手区 Excel 创建、读取、写入

GRUNMI · 2017年05月25日 · 最后由 GRUNMI 回复于 2017年06月02日 · 1896 次阅读

参考资料:
http://www.python-excel.org/

创建 Excel 和写入内容
需要安装 xlwt
使用 pip 安装,命令如下:
pip install xlwt
代码实现如下:

import xlwt
# 初始化表名,位置,名称
def writeexcel(sheetname='sheet1', filepath='C:\\Users\\Administrator\\Desktop\\', filename='test.xlsx'):
    test = xlwt.Workbook()  # 创建工作簿
    sheet1 = test.add_sheet(sheetname)  # 添加表
    # 单元格中添加内容
    superpition = 0
    for r in range(0, 10):
        for c in range(0, 10):
            sheet1.write(r, c, 'test%d' % superpition)
            superpition += 1
    # 保存的位置名称
    test.save(filepath+filename)
if __name__ == '__main__':
    writeexcel()

最终效果:

读取 Excel
需要安装 xlrd
使用 pip 安装 xlrd,命令如下:
pip install xlrd
实现的代码如下:

def openexcle(path):
    table = xlrd.open_workbook(path)
    num = table.sheet_names()  # 获取所有sheet名称
    print(num)
    # sheet1 = table.sheet_by_name(u'sheet1')  # 打开sheet1表
    sheet1 = table.sheet_by_name(num[0])  # 打开第一张表
    '''
    只读模式不能直接通过get_sheet获取表
    table.get_sheet(0)
    '''


    nrows = sheet1.nrows  # 获取行
    for i in range(nrows):
        print(sheet1.row_values(i))  # 打印行中的值

    ncols = sheet1.ncols  # 获取列
    for n in range(ncols):
        print(sheet1.col_values(n))

if __name__ == '__main__':
    openexcle('C:\\Users\\Administrator\\Desktop\\test.xlsx')

打印结果:

在存在的 Excel 中,写入内容
需要安装 xlutils 库,引用 copy 模块
使用 pip 安装 xlutils,命令如下:
pip install xlutils
实现的代码如下:

import xlrd
from xlutils.copy import copy
def writeexcel(filepath, text):
    workbook = xlrd.open_workbook(filepath)  # 打开excel
    data = copy(workbook)  # 复制工作簿
    newdata = data.get_sheet(0)  # 获取第一个sheet
    newdata.write(11, 11, text)  # 第(11,11)单元格中写入text
    data.save("C:\\Users\\Administrator\\Desktop\\test.xlsx")  # 保存到test.xlsx中
if __name__ == '__main__':
    writeexcel("C:\\Users\\Administrator\\Desktop\\test.xlsx", "test")

东拼西凑,如有更好的方法,请告知

共收到 8 条回复 时间 点赞

我之前帮同学写过一个合并报表的代码。
写进 excel 的时候记录当前的行,写下一条的时候往下写就行了啊。。

纯稀饭 回复

嗯嗯,谢谢啊😃

import openpyxl 可以读写 excel 还能修改字体等等

谢谢分享经验~~太高深的看不懂, 就喜欢你这种容易上手的帖子

匿名 #4 · 2017年06月01日

xlxswritter 这个库也不错,写入内容,插入表格,自定义样式,推荐推荐

Zhhh 回复

谢谢,我去学习下

谢谢哈,去学习下

zhang 回复

哈哈,刚学习的

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册