用python操作excel(读写)

用python操作excel(读写)

import xlrd
import random
from xlutils.copy import copy
import xlutils
# https://github.com/python-excel/xlrd
# https://xlrd.readthedocs.io/en/latest/api.html


def test1():
    file = xlrd.open_workbook(filename=r'1.xlsx')
    print(file.sheet_names())
    # 获取工作表的名称
    table = file.sheets()[0]
    # 通过索引顺序获取
    table = file.sheet_by_index(sheetx=0)
    # 通过索引顺序获取
    table = file.sheet_by_name(sheet_name='Sheet1')
    # 通过名称获取
    print("{0} {1} {2}".format(table.name, table.nrows, table.ncols))
    # 打印工作表的名称,表的总行数,表的总列数
    print("Cell A18 is {0}".format(table.cell_value(rowx=17, colx=0)))
    # 打印单元格的值


def test2():
    x = random.random()
    x = round(number=x, ndigits=1) # 保留一位小数
    print(x)


def main():
    file = xlrd.open_workbook(filename=r'1.xlsx')
    table = file.sheets()[0]
    wb = copy(wb=file)
    for i in range(1, table.nrows):
        x = random.uniform(0.1, 0.5) + 29
        wb.get_sheet(0).write(i, 2, round(number=x, ndigits=1))
    wb.save('2.xlsx')


if __name__ == '__main__':
    main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值