有没有办法用os.walk或glob来简化它?
from win32com.client import Dispatch
inputwb1 = "D:/apera/Workspace/Sounding/sounding001.xlsx"
inputwb2 = "D:/apera/Workspace/Sounding/sounding002.xlsx"
Sheet = 'OUTPUT'
excel = Dispatch("Excel.Application")
source = excel.Workbooks.Open(inputwb1)
source.Worksheets(Sheet).Range('F1:H500').Copy()
source.Worksheets(Sheet).Range('I1:K500').PasteSpecial(Paste=-4163)
source = excel.Workbooks.Open(inputwb2)
source.Worksheets(Sheet).Range('F1:H500').Copy()
source.Worksheets(Sheet).Range('I1:K500').PasteSpecial(Paste=-4163)
因为如果我想写数百个,这个东西会占用太多空间。感谢您的帮助
答案 0 :(得分:1)
你好像几乎回答了你自己的问题。这样的事情可能会这样做:
import glob
from win32com.client import Dispatch
Sheet = 'OUTPUT'
excel = Dispatch("Excel.Application")
for filename in glob.glob("D:/apera/Workspace/Sounding/sounding*.xlsx"):
source = excel.Workbooks.Open(filename)
source.Worksheets(Sheet).Range('F1:H500').Copy()
source.Worksheets(Sheet).Range('I1:K500').PasteSpecial(Paste=-4163)
答案 1 :(得分:1)
你可以像这样打开多个excel文件(例子):
import win32com.client
import os
path = ('D:\\New Folder\\MyExcelFiles\\')
fileslist = os.listdir('D:\\New Folder\\MyExcelFiles\\')
xl = win32com.client.DispatchEx('Excel.Application')
xl.Visible = True
for i in fileslist :
xl.Workbooks.Open(path+i)
if xl.Cells.Find('2014'):
xl.Cells.Replace('2015')
xl.Save()
xl.Workbooks.Close()
else:
xl.Workbooks.Close()