在python循环中编辑Excel工作表

时间:2018-04-09 08:52:10

标签: python excel xlwings

我可以使用xlwings编辑Excel文件:

SELECT T1.country, 
       T1.year, 
       T1.month,
       T1.booked,
       T2.checkedout, 
      (T1.booked + T2.checkedout) AS 'sum(booking+checkout)'
FROM 
(
SELECT hotel.country, time.year, time.month, COUNT(booking.room_id) as booked 

FROM booking 
LEFT JOIN room on room.room_id = booking.room_id 

LEFT JOIN hotel on room.hotel_id = hotel.hotel_id 

LEFT JOIN time on booking.time_id = time.time_id 

GROUP BY hotel.country, time.year, time.month 

ORDER by hotel.country, time.year, time.month
) AS T1
INNER JOIN
(
SELECT hotel.country, time.year, time.month, COUNT(checkout.room_id) as checkedout

FROM checkout

LEFT JOIN room on room.room_id = checkout.room_id

LEFT JOIN hotel on room.hotel_id = hotel.hotel_id

LEFT JOIN time on checkout.time_id = time.time_id

GROUP BY hotel.country, time.year, time.month

ORDER BY hotel.country, time.year, time.month
)AS T2
ON T1.country=T2.country
AND T1.year=T2.year
AND T1.month=T2.month

如何在不必手动编写列表的情况下迭代行?另外,有没有办法迭代列?

编辑:编辑单元格区域现在可以正常工作。

import xlwings as xw

filepath = ('file.xlsx')
wb = xw.Workbook(filepath)

sh = 'Sheet1'
l = ['B6','B7','B8','B9','B10','B11']

for i in range(len(l)):
    xw.Range(sh, l[i]).value = i

enter image description here

问题:在此过程中每个单元格都已更改。如何更改一个,然后转到下一个?

1 个答案:

答案 0 :(得分:1)

是的,有一种方法,但是我会高度鼓励你阅读documentation,并亲自尝试。

以下是您正在寻找的内容:

<强>范围

xlwings.Range(cell1 = None,cell2 = None,** options) 返回表示单元格或单元格范围的Range对象。

<强>参数 cell1 (str或tuple或Range) - A1表示法中左上角的范围名称或索引元组或名称或xw.Range对象的范围名称。它还可以使用范围运算符(冒号)指定范围,例如。 “A1:B2” cell2(str或tuple或Range,默认为None) - A1表示法右下角或作为索引元组或作为名称或xw.Range对象的范围名称。

修改

Range()不是可迭代对象吗?如果是这样,你可以这样使用:

for cell in Range(sh , (3,2),(10,2)):
    cell.value = 10