python 读写Excel文件

    import xlrd, xlwt
    def read_xlsx_content(filename):
        # xlxs文件格式,手机, 地址, 姓名, 身份证, 账号, 邮箱
        # 从第二行开始读文件内容
        wb = xlrd.open_workbook(filename)
        booksheet = wb.sheet_by_name('Sheet1')
        content = list()
        for row in range(1, booksheet.nrows):
            row_data = []
            for col in range(booksheet.ncols):
                cel = booksheet.cell(row, col)
                val = cel.value
                if type(val) == float:
                    val = int(val)
                else:
                    val = str(val)
                row_data.append(val)
            content.append(row_data)
        return content


    def write2xlxs(filename, data):
        #  data [[], [], []...]
        #
        wbk = xlwt.Workbook()
        font0 = xlwt.Font()
        font0.name = 'Times New Roman'
        font0.colour_index = 2
        font0.bold = True

        style0 = xlwt.XFStyle()
        style0.font = font0
        sheet1 = wbk.add_sheet('Sheet 1', cell_overwrite_ok=True)
        nrow = 0
        for i in data:
            ncol = 0
            for j in i:
                if isinstance(j, tuple):
                    sheet1.write(nrow, ncol, j[0], style0) if j[-1] == 1 \
                        else sheet1.write(nrow, ncol, j[0])
                else:
                    sheet1.write(nrow, ncol, j)
                ncol += 1
            nrow += 1
        wbk.save(filename)

你可能感兴趣的:(python 读写Excel文件)