如何根据元组值索引使用openpyxl修改xlsm文件中工作表中的单元格

时间:2019-07-10 04:35:12

标签: python regex pandas

我正在熊猫xlsmdataframe变量的帮助下,尝试修改现有tuple文件中的一些新值

因此,我注意到openpyxl库可以根据我之前的问题how to update existing xlsm sheet with macros using pandas, openpyxl, xlwings without losing macros

来修改xlsm工作簿

根据这个问题How write to xlsm using openpyxl,我试图创建此代码,以便通过这种方式通过tuple.value.index修改所需的数据。

# This is my directory                         
mydir = (os.getcwd()).replace('\\', '/') + '/' 
#This is my xlsm file
gov_wb = load_workbook(filename=r'' + mydir + 'Governance_Tracker - Copy 
- Copy.xlsm', read_only=False, keep_vba=True)
#This is sheet I want to modify
gov_trcker = gov_wb['Gov_Tracker']                                                                                    
gov_trcker.cell(row=values.index("%s"), column=31).value = 
'ExampleExampleExampleExample'                             
gov_wb.save('outfile.xlsm')

但我发现此错误

Traceback (most recent call last):
File "C:/Users/mwx707566/PycharmProjects/MyRobotAutomate/MyRobotFunc.py", 
line 115, in <module>
gov_trcker.cell(row=values.index("%s"), column=31).value = 'dsfgdsgvdf'
ValueError: tuple.index(x): x not in tuple

任何想法如何在不丢失宏的情况下修改现有xlsm文件

注意:我上一个问题中的任何信息 how to update existing xlsm sheet with macros using pandas, openpyxl, xlwings without losing macros

编辑

我也喜欢这份sheet cell object文档。 https://pythonhosted.org/xlrd3/cell.html,但仍然找不到任何def接受tuple的建议吗?

编辑2

根据Muhammad Adeel脚本,我根据需要遵循他的脚本,这是我的代码

import sys
import xlrd
import unicodedata
import base64
import decimal
import glob
import csv
import xlwt
import os
import xlutils
from xlutils.copy import copy as xl_copy

reload(sys)

mydir = (os.getcwd()).replace('\\', '/') + '/'
myPath = mydir + 'Governance_Tracker - Copy - Copy.xlsm'

if not os.path.exists(myPath):
gov_wb = xlwt.Workbook(encoding='ascii')
else:
   upd_b = xlrd.open_workbook(myPath)
   gov_wb = xl_copy(upd_b)
   sheets = upd_b.sheets()

last_sheet_index = len(sheets)
xl_sheet = upd_b.sheet_by_index(last_sheet_index - 1)
print ('Sheet name: %s' % xl_sheet.name)

for i in range(1, xl_sheet.nrows):
    previous_day_data.append(xl_sheet.row(i))
sheet_names = []
for x in sheets:
  sheet_names.append(x.name)

if new_worksheet_name in sheet_names:
    print 'THE SHEET ALREADY PRESENT WITH THE SAME DATE.. KINDLY DELETE 
THAT'
return

worksheet = gov_wb.add_sheet(new_worksheet_name)

rowHeaders = [
"#", "Site Name", "Region", "Site Type", "SiteCode", "TAC Name", 
"DT\nReadiness", "RFS Date", "RFS"
, "Huawei 1st submission date ", "TE 1st Response date ", "Huawei 2nd 
submission date ", "TE 2nd Response date ",
"Huawei 3rd submission date ", "TE 3rd Response date ", "Acceptance 
Date(Optimization)", "Acceptance Date(Planning)", "signed sites",
"As Built Date", "AS built status", "Date DT", "DT Status", "SHR Status", 
"DT Planned", "Integeration Status", "Comments/snags",
"Cluster name", "Type(Standalone/colocated)", "Installed type 
(Standalone/colocated)", " Status ", "Pending  ", "Pending Status",
"problematic details", "ETS TAC \n", "Region", "SF6\n Signed date", "SF6\n 
Signed Comment", " Comment History",
"On air Owner", "PP \nOwner", "Report \nComment", "HU Opt.\nArea Owner", 
"Planning Owner", "PO Number", "Trigger date ",
"As built status", "R", "T"
]

gov_tracker = gov_wb.get_sheet(0)
trend = gov_wb.get_sheet(2)
shee_planning = gov_wb.get_sheet(3)
all = gov_wb.get_sheet(4)
data = gov_wb.get_sheet(5)
sheet5 = gov_wb.get_sheet(6)
charts = gov_wb.get_sheet(7)
ssv_progress_tracker = gov_wb.get_sheet(8)
shrs_tracker_te_huawei = gov_wb.get_sheet(9)

global row
for index, value in enumerate(rowHeaders):
  worksheet.write(row, index, value)

for index, value in enumerate(alp_total_rowValues):  # populate other 
excel sheets
  gov_tracker.write(row, index, value)
gov_wb.save(mydir)

这是根据我的需要遵循Mohammed Adeel脚本之后的代码,但是我陷入了previous_day_datanew_worksheet_namealp_total_rowValues的困境,如何根据我的需要

这里有什么想法吗? 有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

几个月前,我已经创建了一个脚本,用于更新现有的excel文件,它会在此excel文件上添加新工作表以及更新现有的excel工作表。我将附加相关的代码,希望您从该代码中得到启发。

if not os.path.exists(file_name):
    wb = xlwt.Workbook(encoding = 'ascii')
else:
    rb = xlrd.open_workbook(file_name)
    wb = xl_copy(rb)
    sheets = rb.sheets()

last_sheet_index =  len(sheets)
xl_sheet = rb.sheet_by_index(last_sheet_index-1)
print ('Sheet name: %s' % xl_sheet.name)

for i in range(1, xl_sheet.nrows):
    previous_day_data.append(xl_sheet.row(i)) 
sheet_names = []
for x in sheets:
sheet_names.append(x.name)

if new_worksheet_name in sheet_names:
  print 'THE SHEET ALREADY PRESENT WITH THE SAME DATE.. KINDLY DELETE THAT'
  return

worksheet = wb.add_sheet(new_worksheet_name)

rowHeaders = ["Item #", "Title", "Price", ....]

alp_total_sheet = wb.get_sheet(0)
alp_price_sheet = wb.get_sheet(1)
fairless_sheet  = wb.get_sheet(2)
atlanta_sheet   = wb.get_sheet(3)
dallas_sheet    = wb.get_sheet(4)
eagan_sheet     = wb.get_sheet(5)
sparks_sheet    = wb.get_sheet(6)

global row 
for index, value in enumerate(rowHeaders):
  worksheet.write(row, index, value)

for index, value in enumerate(alp_total_rowValues): # populate other excel sheets
    alp_total_sheet.write(row, index, value)
wb.save(file_name)