0

我想打印网络共享(M:驱动器)上的剩余空间量(以 GB 为单位),然后获取该值并将其添加到 Excel 电子表格中。我对编程很陌生,需要我能得到的所有帮助!

提前致谢

编辑:

这是我到目前为止所管理的。

import ctypes
from win32com.client import Dispatch
import pythoncom

def drivespace():
    #get space in bytes
    free_bytes = ctypes.c_ulonglong(0)
    ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(u'M:\\'), None, None ctypes.pointer(free_bytes))

    #calculate space in GB
    free_GB = free_bytes.value/1024/1024/1024
    print(free_GB)

    #input data to Excel
    xl = Dispatch ('Excel.Application')
    xl.visible = 0
    xl.Workbooks.Add (r'C:\Location\Location1\Location2\Book1.xlsm')
    xl.Run('Down1') #macro inside the workbook, just to move the cell down 1 row
    #here is where I need some help... something to input the data to the active cell
    #xl.Cells( ?? ACTIVE CELL HERE BUT DON'T KNOW HOW ?? ).value=(free_GB)
    xl.Quit()

    #release held Excel process
    pythoncom.CoUninitialize()

所以基本上,除了将数据实际打印到活动单元格之外,我已经对所有内容进行了排序。有没有人有任何 pywin32 知识可以帮助我做到这一点?

非常感谢!

4

2 回答 2

1

Edited following comment

import ctypes, os, pythoncom
from win32com.client import Dispatch

def drivespace(drive, xl_path, col):
    #get space in bytes
    free_bytes = ctypes.c_ulonglong(0)
    ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(drive), \
                                               None, None, ctypes.pointer(free_bytes))

    #calculate space in GB
    free_GB = free_bytes.value/1024/1024/1024
    print(free_GB)

    #input data to Excel
    xl = Dispatch('Excel.Application')
    xl.visible = 0
    wb = xl.Workbooks.Open(xl_path)
    ws = wb.Worksheets(1)

    # initialise values
    empty = False
    row = 1

    # loop until first empty cell in this column
    while not empty:
        val = ws.Range(col+str(row)).value
        print val
        if val == None:
            print "Found first empty cell! Writing Value..."
            ws.Range(col+str(row)).value = free_GB
            empty = True
        row += 1

    wb.Close(True)
    xl.Quit()

    #release held Excel process
    pythoncom.CoUninitialize()

def main():
    drive = 'C:\\'
    xl_path = os.path.join(os.getenv('so'),'free_space_to_excel','Book1.xlsm')
    xl_column = 'A'
    drivespace(drive, xl_path, xl_column)

if __name__ == '__main__':
    main()

You will just need to change the values in the main procedure to set them to your drive, xl_path etc. This takes an additional arguement for a column letter and finds the first available cell in that column. I think this is a safer approach than relying on a particular cell being active when you open the sheet.

于 2013-09-13T15:47:31.203 回答
0

我认为您可能需要将其分解为子问题,对每个问题进行尝试,并针对您遇到的任何问题发布问题,包括您在帖子中的尝试。以下是一些建议的步骤和需要研究的领域:

  1. 计算驱动器上剩余的空间。这里有一个线程可能对此有所帮助。
  2. 要写入 Excel,有一个名为 xlwt 的模块,可以从这里下载。我还在这里找到了使用它的简短教程。

编辑

对于 Python 3.x,我找到了一个值得一试的 xlwt 端口。我在这里找到了一个指向 github 存储库帖子。我看不到安装程序,但从源代码构建应该很简单。

您需要从这个 github 页面下载所有内容到一个文件夹中,然后从命令行 cd 到该目录并运行

Python setup.py install
于 2013-09-13T11:59:14.880 回答