xlDoc = win32com.client.gencache.EnsureDispatch("Excel.Application")
writefile=xlDoc.Workbooks.Open("M:\Python automation\Main.xlsx")
count = writefile.Sheets.Count
print "count", count
Sheetcount=count-1
for i,sht in enumerate(writefile.Sheets):
print "i",i
if i==0:
print ""
else:
xlDoc.Worksheets(sht.Name).Activate()
xlSht = xlDoc.ActiveSheet
name=xlSht.Name
filename =os.path.join(dir,name+".xlsx")
print filename
key=i+1
data[key]= ReadData(filename)
#To read data from excel
def ReadData(filename):
xlApp = Dispatch("Excel.Application")
xlApp.Quit() #Close excel sheet if open
xlApp.Visible=False
##xlWb = xlApp.Workbooks.Open(filename)
print "Reading "
DataTemp = []
xlWb = xlApp.Workbooks.Open(filename)
Sheet= xlWb.Sheets(1)
used = Sheet.UsedRange
nrows = used.Row + used.Rows.Count - 1
ncols = used.Column + used.Columns.Count - 1
while (Sheet.Cells(nrows,1).Value) != None:
nrows += nrows
#Read all data
DataTuple = Sheet.Range("A2:N%d" % nrows).Value
DataList = [list(x) for x in DataTuple]
for rowA in DataList:
for n,i in enumerate(rowA):
if i == None:
rowA[n] = ''
DataTemp.append(rowA)
xlWb.Close(True)
xlApp.Application.Quit()
return DataTemp
我必须读取Excel主文件的工作表名称,并使用这些名称读取文件夹中的相应Excel文件并将数据存储到字典中。在读取第一个excel文件之后,我当前的代码不再读取任何excel文件。
主excel文件有4张纸,但仅继续读取第二张纸“ Bon”,然后停止。
输出:
PS M:\ Python自动化> python try.py
数4
我0
i 1
M:\ Python自动化\ Bon.xlsx
阅读
PS M:\ Python自动化>