如何用 win32com 打开多个 excel 个文件?
How to open multiple excel files with win32com?
有没有办法用 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)
因为这个东西我要写几百个就得花这么多space
您似乎几乎已经回答了您自己的问题。像这样的事情可能会做到:
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)
您可以像这样打开多个 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()
有没有办法用 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)
因为这个东西我要写几百个就得花这么多space
您似乎几乎已经回答了您自己的问题。像这样的事情可能会做到:
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)
您可以像这样打开多个 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()