欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python不改變Excel單元格樣式方式—xls和xlsx兩種格式

 更新時間:2023年06月21日 10:13:15   作者:KaiKai-G  
這篇文章主要介紹了Python不改變Excel單元格樣式方式—xls和xlsx兩種格式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

Python不改變Excel單元格樣式—xls和xlsx兩種格式

因為xls和xlsx兩種格式,xlsx是被加密了傳統(tǒng)的方式讀取修改不了

  • 下面是xls格式讀取修改
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name:         test_excel
# Description:
# Author:       GLK
# Date:         2021/7/7
# -------------------------------------------------------------------------------
import xlrd
import os
import datetime
from xlutils.filter import process, XLRDReader, XLWTWriter
#修改表內(nèi)容
def update_sheet(sheet,sheet_copy,style_list):
    if sheet.name != '模板':
        # 得到這個表單自己寫的內(nèi)容的個數(shù)(因為每個人表格行數(shù)個數(shù)都不同,所以沒法定位自己寫了幾個)
        # rows = sheet.nrows - 11
        # 得到一個自己寫的列表
        print(f"表單名:{sheet.name}", end=" ")
        print(f"行數(shù):{sheet.nrows}", end=" ")
        print(f"列數(shù):{sheet.ncols}", end=" ")
        # print(f"自己寫的內(nèi)容個數(shù):{rows}", end=" ")
        # 得到一個單元格的索引位置的格式
        style = style_list[sheet.cell_xf_index(4, 8)]
        print("工時內(nèi)容分別為:",end="")
        #根據(jù)觀察最多是寫了5個工時內(nèi)容
        for i in range(0,5):
            # 得到這一單元格的內(nèi)容
            value = sheet.cell_value(4 + i, 8)
            if value != "":
                print(value,end=",")
                # 按照上面的格式修改單元格
                sheet_copy.write(4 + i, 6, value, style)
        print("  工時日志修改成功!")
#通過地址定位到表
def select_sheet(addr,date):
    try:
        rb = xlrd.open_workbook(addr, formatting_info=True)
        # 參考xlutils.copy庫內(nèi)的用法 參考xlutils.filter內(nèi)的參數(shù)定義style_list(相當(dāng)于拆分copy方法)
        w = XLWTWriter()
        process(XLRDReader(rb, addr), w)
        wb = w.output[0][1]
        style_list = w.style_list
        try:
            # 原本的表   (通過名字查找)
            sheet = rb.sheet_by_name(date)
            # 復(fù)制出來的表 (通過名字查找)
            sheet_copy = wb.get_sheet(date)
        except:
            print("表名不存在,可能是周六日")
        #修改表
        update_sheet(sheet,sheet_copy,style_list)
        wb.save(addr)
    except:
        print("非xls格式的文件")
#讀取目錄下所有的文件名放到result中
def get_all_word(cwd):
    work_time = []
    get_dir = os.listdir(cwd)
    for i in get_dir:
        sub_dir = os.path.join(cwd,i)
        if os.path.isdir(sub_dir):
            get_all_word(sub_dir)
        else:
            work_time.append(i)
    return work_time
#得到當(dāng)前時間起一周前的時間表名
def get_date_week():
    #得到今天的時間
    today = datetime.date.today()
    #將當(dāng)前日期一周的時間放到list中
    week_time = [str(today - datetime.timedelta(days =7 - w)) for w in range(1, 8)]
    #因為格式問題 需要替換掉 "-"
    day_time = []
    for day in week_time:
        replace = day.replace("-", "")
        day_time.append(replace)
    print("當(dāng)前一周的表單名為:",day_time)
    return day_time
if __name__ == '__main__':
    print("======請將所有.xls格式的工時日志文件放到'D:\工時日志'下=======")
    print()
    # 1、存放全部excel的目錄地址
    addr = r'D:\\工時日志\\'
    #2、得到addr目錄下所有的文件
    work_time = get_all_word(addr)
    print('"D:\工時日志"目錄下的文件有:',work_time)
    #3、得到當(dāng)前一周的表名
    week_time = get_date_week()
    print()
    #4、遍歷每個表
    for date in week_time:
        for work_t in work_time:
            # 拼接
            addr_work = addr + work_t
            print("正在修改的文件為:",work_t,end=" ")
            #傳入地址和要修改的表名
            select_sheet(addr_work, date)
        print("#############################")
    print("全部修改完成!")
  • xlsx
# -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# Name:         test_excel
# Description:  
# Author:       GLK
# Date:         2021/7/6
#-------------------------------------------------------------------------------
import openpyxl
import os
#讀取并修改excel工時
def update(wb,time):
    try:
        sheet = wb[time]
        if sheet.title != '模板':
            #得到這個表單自己寫的內(nèi)容的個數(shù)(總長度減去固定的表格長度就是自己添加的個數(shù))
            rows = sheet.max_row - 11
            #得到一個自己寫的列表
            print(f"名:{sheet.title}",end=" ")
            print(f"行:{sheet.max_row}",end=" ")
            print(f"列:{sheet.max_column}",end=" ")
            for i in range(0,5): #通過遍歷個數(shù)得到索引到每個位置進(jìn)行讀取和修改
                xl_cell = sheet.cell(row=5+i, column=9).value
                sheet.cell(row=5+i, column=7,value=xl_cell)
                print(f"工時內(nèi)容:{xl_cell}",end=",")
            print()
    except:
        print("表不存在")
#加載excel文件并修改設(shè)置時間
def excel_work(addr_work,date):
    # 加載 excel 文件
    print(addr_work)
    try:
        wb = openpyxl.load_workbook(addr_work)
        update(wb,date)
        wb.save(addr_work)
    except:
        print("不是.xlsx格式")
#讀取目錄下所有的文件名放到work_time中
def get_all_word(cwd):
    work_time = []
    get_dir = os.listdir(cwd)
    for i in get_dir:
        sub_dir = os.path.join(cwd,i)
        if os.path.isdir(sub_dir):
            get_all_word(sub_dir)
        else:
            work_time.append(i)
    return work_time
if __name__ == '__main__':
    #存放全部excel的目錄地址
    addr = r'D:\\工時日志\\'
    #將當(dāng)前目錄下的文件名放到list中
    work_time = get_all_word(addr)
    print(work_time)
    date = input("請輸入需要修改的日期:")
    for work_t in work_time:
        #拼接
        addr_work = addr + work_t
        excel_work(addr_work,date)
    # active = wb.active
    # print(active)
    #
    # # 得到sheet對象
    # sheet = wb['20210701']
    #
    # sheet['A1'] = '修改'
    # sheet['C%d'%(5)] = 'aaaaaaaaaaa'
    #
    # ## 指定不同的文件名,可以另存為別的文件
    # wb.save(r'D:\工時日志\工作簿1.xlsx')

python寫數(shù)據(jù)到excel,不改變原有樣式

問題\場景\需求

python 讀取excel之后,格式就復(fù)原了,怎么讓格式不變

解決\目標(biāo)

目標(biāo):python寫數(shù)據(jù)到excel,不改變原有樣式

解決:在打開excel時,加入該參數(shù) formatting_info=True

from xlrd import open_workbook
 r_xls = open_workbook(fileName,formatting_info=True)  # 讀取excel文件
 row = r_xls.sheets()[sheet].nrows  # 獲取已有的行數(shù)
 excel.save(fileName) # 保存
 def table_data_list(self):
        """獲取table數(shù)據(jù),返回一個json"""
        par_ids_list, sec_ids_list, dep_ids_list, job_list, major_list = [], [], [], [], []
        en_master_qty_list, en_un_qty_list, ex_master_qty_list, ex_un_qty_list, notes_list = [], [], [], [], []
        count_num = 0
        if self:
            for line in self.line_ids:
                major_name = line.major_ids.mapped('name')
                par_ids_list.append(line.parent_company_id.name)
                sec_ids_list.append(line.secondary_company_id.name)
                dep_ids_list.append(line.department_name)
                job_list.append(line.job)
                major_list.append(','.join(major_name))
                en_master_qty_list.append(line.en_master_qty)
                en_un_qty_list.append(line.en_undergraduate_qty)
                ex_master_qty_list.append(line.ex_master_qty)
                ex_un_qty_list.append(line.ex_undergraduate_qty)
                notes_list.append(line.notes)
                count_num += 1
        data_array = {
            'id': self.id,
            'tab_name': self.name,
            'count_num': count_num,
            'sec_ids_list': sec_ids_list,
            'par_ids_list': par_ids_list,
            'dep_ids_list': dep_ids_list,
            'job_list': job_list,
            'major_list': major_list,
            'en_master_qty_list': en_master_qty_list,
            'en_un_qty_list': en_un_qty_list,
            'ex_master_qty_list': ex_master_qty_list,
            'ex_un_qty_list': ex_un_qty_list,
            'notes_list': notes_list,
        }
        return data_array
    def btn_excl_method(self):
        """導(dǎo)出excel入口函數(shù)"""
        data_array = self.table_data_list()
        context = dict(self._context or {})
        wiz_obj = self.env['hd.export.export.data.wizard']
        filename = '計劃編制-%s' % (datetime.datetime.today())
        wiz_id = wiz_obj.sudo().create({
            'file_data': self.file_data_excel(data_array)
        })
        value = dict(
            type='ir.actions.act_url',
            target='self',
            url='/web/content?model=%s&id=%s&field=file_data&download=true&filename=%s.xls' % (
                'hd.export.export.data.wizard', wiz_id.id, filename),
        )
        return value
    def file_data_excel(self, data_array):
        # 1、使用xlrd打開Excel
        workbook1 = open_workbook(
            "E:\\HD_Settled\\dtcloud360\\appstore\\dtcloud_hd_graduate\\static\\src\\download\\hd.graduate.application.line.xlsx")
        # 2、使用xlutils模塊的copy復(fù)制打開的文件,并保留原格式
        open_mb_file_cp = copy.copy(workbook1)
        # 3、使用下標(biāo)定位的方式定位到Excel工作簿里的工作表
        worksheet = open_mb_file_cp.get_sheet(0)
        count_num = data_array['count_num']
        if count_num > 0:
            for row in range(1, count_num + 1):
                rews = row - 1
                worksheet.write(row, 0, data_array['sec_ids_list'][rews] or '')
                worksheet.write(row, 1, data_array['par_ids_list'][rews] or '')
                worksheet.write(row, 2, data_array['dep_ids_list'][rews] or '')
                worksheet.write(row, 3, data_array['job_list'][rews] or '')
                worksheet.write(row, 4, data_array['major_list'][rews] or '')
                worksheet.write(row, 5, data_array['en_master_qty_list'][rews])
                worksheet.write(row, 6, data_array['en_un_qty_list'][rews])
                worksheet.write(row, 7, data_array['ex_master_qty_list'][rews])
                worksheet.write(row, 8, data_array['ex_un_qty_list'][rews])
                worksheet.write(row, 9, data_array['notes_list'][rews] or '')
        buffer = BytesIO()
        open_mb_file_cp.save(buffer)
        return base64.encodebytes(buffer.getvalue())

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 全面解讀Python Web開發(fā)框架Django

    全面解讀Python Web開發(fā)框架Django

    Django是一個開源的Web應(yīng)用框架,由Python寫成。采用MVC的軟件設(shè)計模式,主要目標(biāo)是使得開發(fā)復(fù)雜的、數(shù)據(jù)庫驅(qū)動的網(wǎng)站變得簡單。Django注重組件的重用性和“可插拔性”,敏捷開發(fā)和DRY法則(Don’t Repeat Yoursef)。
    2014-06-06
  • Python sklearn KFold 生成交叉驗證數(shù)據(jù)集的方法

    Python sklearn KFold 生成交叉驗證數(shù)據(jù)集的方法

    今天小編就為大家分享一篇Python sklearn KFold 生成交叉驗證數(shù)據(jù)集的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • python之cv2與圖像的載入、顯示和保存實例

    python之cv2與圖像的載入、顯示和保存實例

    今天小編就為大家分享一篇python之cv2與圖像的載入、顯示和保存實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • OpenCV利用手勢識別實現(xiàn)虛擬拖放效果

    OpenCV利用手勢識別實現(xiàn)虛擬拖放效果

    這篇文章主要介紹了利用OpenCV實現(xiàn)手勢識別,從而進(jìn)行虛擬拖放效果,我們可以使用這個技術(shù)實現(xiàn)一些游戲,控制機械臂等很多有趣的事情。感興趣的可以學(xué)習(xí)一下
    2022-01-01
  • Python學(xué)習(xí)之configparser模塊的使用詳解

    Python學(xué)習(xí)之configparser模塊的使用詳解

    ConfigParser是用來讀取配置文件的包。這篇文章主要通過一些簡單的實例帶大家了解一下ConfigParser模塊的具體使用,感興趣的小伙伴跟隨小編一起了解一下
    2023-01-01
  • Python中類方法@classmethod和靜態(tài)方法@staticmethod解析

    Python中類方法@classmethod和靜態(tài)方法@staticmethod解析

    這篇文章主要介紹了Python中類方法@classmethod和靜態(tài)方法@staticmethod解析,python中存在三種方法,分別為常規(guī)方法(定義中傳入self)、@classmethod修飾的類方法、@staticmethod修飾的靜態(tài)方法,,需要的朋友可以參考下
    2023-08-08
  • Python中NumPy的數(shù)組重塑

    Python中NumPy的數(shù)組重塑

    這篇文章主要介紹了Python中NumPy的數(shù)組重塑,Numpy是Python科學(xué)計算庫,用于快速處理任意維度的數(shù)組,NumPy使用c語言寫的,底部解除了GIL,其對數(shù)組的操作速度不在受python解釋器限制<BR>
    2023-07-07
  • 對python3 一組數(shù)值的歸一化處理方法詳解

    對python3 一組數(shù)值的歸一化處理方法詳解

    今天小編就為大家分享一篇對python3 一組數(shù)值的歸一化處理方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • python?datetime模塊詳解

    python?datetime模塊詳解

    Python中常用于時間的模塊有time、datetime 和 calendar,顧名思義 time 是表示時間(時、分、秒、毫秒)等,calendar 是表示日歷時間的,本章先討論 datetime 模塊,需要的朋友可以參考下
    2022-06-06
  • python元組簡單介紹

    python元組簡單介紹

    這篇文章主要給大家分享中得python基礎(chǔ) 元組,元組的特點是一種不可變序列,一旦創(chuàng)建就不能修改,帶著些許了解和小編一起進(jìn)入文章得具體內(nèi)容吧
    2021-10-10

最新評論