python操作excel表格

如果是老一点的xls版本的excel 使用xlwt xlrd
如果是新一点的xlsx版本的excel使用openpyxl

import xlrd
import xlwt
import openpyxl

def write_03_excel(path):
    wb = xlwt.Workbook()
    sheet = wb.add_sheet("2003测试表")
    value = [
        ["名称","价格","出版社","语言"],
        ["白夜", "22.3", "music", "中文"],
        ["该死的温柔", "32.4", "music", "中文"],
        ["啦啦啦", "26.7", "music", "中文"]
    ]
    for i in range(4):  # 总共4 行数据
        for j in range(0,len(value[i])):  # 每一行列表里面有多少项
            sheet.write(i,j,value[i][j])
    wb.save(path)
    print("2003写入数据成功")


def read_03_excel(path):
    workbook = xlrd.open_workbook(path)
    sheets = workbook.sheet_names()
    worksheet = workbook.sheet_by_name(sheets[0])
    for i in range(0,worksheet.nrows):   # worksheet.nrows 获取总共多少行
        row = worksheet.row(i)  # 获取第 i 行
        for j in range(0,worksheet.ncols):  # worksheet.ncols 获取总共多少列
            print(worksheet.cell_value(i,j),"\t",end="")    # 空一个制表符,不换行打印
        print() # 每行末尾打印换行


def write_07_excel(path):
    wb = openpyxl.Workbook()
    sheet = wb.active
    sheet.title = "2007测试表"
    values = [["oid"]]
    for i in range(1,201):
        list1 = [i]
        values.append(list1)
    for i in range(0,len(values)):
        for j in range(0,len(values[i])):
            sheet.cell(row=i+1,column=j+1,value=str(values[i][j]))

    wb.save(path)
    print("写入数据成功!")


def read_07_excel(path):
    wb = openpyxl.load_workbook(path)
    names = wb.sheetnames   # 取到所有的表名字
    sheet = wb[names[0]]   # 拿到第一张表,如果有多个表,使用for i in循环 根据i 拿到表

    for row in sheet.rows:   # sheet.rows 拿到所有行,是一个二维数组,
        # 注意sheet.rows是一个生成器,不能使用列表那样通过下表获取值,只能通过for循环
        for cell in row:   # row 是一行的数据,是一个一维数组,每个元素是一个单元格
            # 注意row不是一个生成器,而是一个元祖,可以通过下表去索引,
            # cell 是属于openpyxl工具类里面的一个cell类,需要通过value来获取里面的值
            print(type(cell))
            print(cell.value, "\t", end="")  # \t 是一个制表符。 每个单元格之间一个制表符隔开,不换行
        print()  # 一行打印完毕之后 换行。

# file_path_2003 = "data/2003.xls"
# file_path_2007 = "data/5b3a01bb1b24780006b1e55f.csv"
file_path_2007 = "data/old.xlsx"

# write_03_excel(file_path_2003)
# read_03_excel(file_path_2003)
#
# write_07_excel(file_path_2007)
read_07_excel(file_path_2007)












你可能感兴趣的:(python操作excel表格)