【问题标题】:Select all the existing sheets from a workbook using pywin32 / How to transform a string input to a list使用 pywin32 从工作簿中选择所有现有工作表/如何将字符串输入转换为列表
【发布时间】:2021-08-11 04:57:17
【问题描述】:

LE:有什么方法可以使用 pywin32 从工作簿中选择所有现有工作表?

我正在使用 win32com.client 打开一个 Excel 工作簿。

我希望用户能够选择多个工作表。

如何将用户的输入转换为列表?

我试过了:

USER_INP = simpledialog.askstring(title="Sheets to be converted",
                                  prompt="How many sheets do you need?")


print(USER_INP)
z = str(USER_INP)




ws_index_list = []

if z == 1:
    ws_index_list = [1]
elif z == 2:
    ws_index_list = [1,2]
elif z == 3:
    ws_index_list = [1,2,3]
elif z == 4:
    ws_index_list = [1,2,3,4]
elif z == 5:
    ws_index_list = [1,2,3,4,5]
elif z == 6:
    ws_index_list = [1,2,3,4,5,6]
elif z == 7:
    ws_index_list = [1,2,3,4,5,6,7]
elif z == 8:
    ws_index_list = [1,2,3,4,5,6,7,8]
elif z == 9:
    ws_index_list = [1,2,3,4,5,6,7,8,9]
elif z == 10:
    ws_index_list = [1,2,3,4,5,6,7,8,9,10]

但它不起作用。如果我给它一个预定义的列表,它会起作用,例如:

ws_index_list = [1,2] 

错误:

 line 75, in <module>
    wb.WorkSheets(ws_index_list).Select()
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\win32com\client\dynamic.py", line 186, in __call__
    return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352571), 1)

另外,为什么如果我想将我的文件导出为“final test 2”,它会得到名称“final%test%2”。如何替换“%”?

PS:我知道我的代码一团糟,这就是我寻求帮助的原因 :) 希望我不会得到任何反对意见

【问题讨论】:

    标签: python-3.x pywin32 win32com


    【解决方案1】:

    解决了

    USER_INP = simpledialog.askstring(title="Sheets to be converted",
                                      prompt="How many sheets do you need?")
    
    
    z = str(USER_INP)
    
    
    
    ws_index_list = []
    
    if z == str(1):
        ws_index_list.extend([1])
    elif z == str(2):
        ws_index_list.extend([1,2])
    elif z == str(3):
        ws_index_list.extend([1,2,3])
    elif z == str(4):
        ws_index_list.extend([1,2,3,4])
    elif z == str(5):
        ws_index_list.extend([1,2,3,4,5])
    elif z == str(6):
        ws_index_list.extend([1,2,3,4,5,6])
    elif z == str(7):
        ws_index_list.extend([1,2,3,4,5,6,7])
    elif z == str(8):
        ws_index_list.extend([1,2,3,4,5,6,7,8])
    elif z == str(9):
        ws_index_list.extend([1,2,3,4,5,6,7,8,9])
    elif z == str(10):
        ws_index_list.extend([1,2,3,4,5,6,7,8,9,10])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      相关资源
      最近更新 更多