python - 将同一范围从一个工作簿多次复制到另一个工作簿
问题描述
根据所附图像,我正在尝试将相同的数据复制并粘贴到不同的格式中。我已经弄清楚了代码的第一部分,但在此评论之后我需要帮助缩写第二部分:
“逐步填写每个商店组的概念”
目前,这段代码效率不高,我想把它压缩成几行。
所需结果的图像(右侧):
这是我到目前为止拼凑的代码:
import openpyxl as xl;
filename ="c:\\Users\kevin\Documents\Python Programs\Excel Python\Conceptlist.xlsx"
wb1 = xl.load_workbook(filename)
ws1 = wb1.worksheets[0]
# opening the destination excel file
filename1 ="c:\\Users\kevin\Documents\Python Programs\Excel Python\Conceptlist2.xlsx"
wb2 = xl.load_workbook(filename1)
ws2 = wb2.worksheets[0]
# copying the cell values from source
# excel file to destination excel file
rowctsq = ws1['A1']
j = 0
while j < rowctsq.value:
j = j + 3
for i in range (3 , 6):
# reading cell value from source excel file
# Populates the store list repeatedly
c = ws1.cell(row = i, column = 1)
ws2.cell(row =i , column = 1).value = c.value
ws2.cell(row =i + j , column = 1).value = c.value
# Fills in the concepts per store group step by step
c = ws1.cell(row = i, column = 2)
ws2.cell(row =i , column = 3).value = c.value
c = ws1.cell(row = i, column = 3)
ws2.cell(row =i + 3 , column = 3).value = c.value
c = ws1.cell(row = i, column = 4)
ws2.cell(row =i + 6 , column = 3).value = c.value
c = ws1.cell(row = i, column = 5)
ws2.cell(row =i + 9 , column = 3).value = c.value
# saving the destination excel file
wb2.save('c:\\Users\kevin\Documents\Python Programs\Excel Python\Conceptlist2.xlsx')
解决方案
希望我能在回答我自己的问题时获得额外的社区积分!我解决了这个问题,并且几乎到达了我的目的地。这是我想出的代码。奇迹般有效。:)
import openpyxl as xl;
filename ="c:\\Users\kevin\Documents\Python Programs\Excel Python\Conceptlist.xlsx"
wb1 = xl.load_workbook(filename)
ws1 = wb1.worksheets[0]
# opening the destination excel file
filename1 ="c:\\Users\kevin\Documents\Python Programs\Excel Python\Conceptlist2.xlsx"
wb2 = xl.load_workbook(filename1)
ws2 = wb2.worksheets[0]
# copying the cell values from source
# excel file to destination excel file
rowctsq = ws1['A1']
j = 0
k = 0
while j < rowctsq.value and k < 6:
j = j + 3
k = k + 1
for i in range (3 , 6):
# reading cell value from source excel file
# Populates store column
c = ws1.cell(row = i, column = 1)
ws2.cell(row =i + j , column = 1).value = c.value
# Populates concept 'x' column
c = ws1.cell(row = i, column = 1 + k)
ws2.cell(row =i + j , column = 3).value = c.value
# Populates concept name column
c = ws1.cell(row = 2, column = 1 + k)
ws2.cell(row =i + j , column = 2).value = c.value
# saving the destination excel file
wb2.save('c:\\Users\kevin\Documents\Python Programs\Excel Python\Conceptlist2.xlsx')
推荐阅读
- haskell - 在 Haskell 中查找四个 10 的所有表达式
- c++ - 我的代码运行良好,但在游戏循环中中断
- list - 字典更新覆盖重复键
- php - Wordpress 标题(使用多个标题)在自定义页面上显示两次
- javascript - ReactJS:如何在服务器中发送多个文件(Laravel)
- android - Kotlin EditText 键监听器仅适用于模拟器
- android - JSON 响应在适配器类上不可读,但在使用改造 http 库的 logcat 上可见
- javascript - 带有 SPA 的 JWT 没有服务器
- c++ - 从服务器到客户端的实时流式传输相机数据
- .net - 将.net 4.5 类库项目的引用添加到.net core 2.1 项目中