实战python 读写EXCEL表

python/EXCEL读取保存

import xlwt
import xlrd
import os


def read_excel(filename):
    row_list = []
    bk = xlrd.open_workbook(filename)
    try:
        sh = bk.sheet_by_name("Sheet1")
    except:
        print("no sheet in %s named Sheet1" % filename)
    else:
        # 获取行数
        nrows = sh.nrows
        # 获取各行数据
        for i in range(1, nrows):
            row_data = sh.row_values(i)
            row_list.append(row_data)
        print(row_list)
        return row_list


class WriteExcel:
    def __init__(self):
        self.work_book = xlwt.Workbook(encoding='utf-8')
        self.sheet = self.work_book.add_sheet('sheet', cell_overwrite_ok=True)
        self.sheet.write(0, 0, u'货号')
        self.sheet.write(0, 1, u'尺码')
        self.sheet.write(0, 2, u'价格')

    def write(self, data_list):
        for index, data in enumerate(data_list):
            count = index + 1
            self.sheet.write(count, 0, data[0])
            self.sheet.write(count, 1, data[1])
            self.sheet.write(count, 2, data[2])

        if os.path.exists('price.xlsx'):
            # 删除指定路径下的文件
            os.remove('price.xlsx')
            print('已将旧数据文件删除')

        self.work_book.save('price.xlsx')
        print('文件保存成功')

posted @ 2020-09-29 18:19  莫贞俊晗  阅读(175)  评论(0编辑  收藏  举报