0

I want to print the amount of space remaining (in GB) on a network share (M: drive), and then take that value and add it to an Excel spreadsheet. I'm very new to programming and need all the help I can get really!

Thanks in advance

EDIT:

Here is what I've managed so far.

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()

So basically, I have everything sorted other than actually printing the data in to the active cell. Does anybody have any pywin32 knowledge that may be able to help me do this?

Thanks a bunch!

Cœur
  • 37,241
  • 25
  • 195
  • 267
ryansin
  • 1,735
  • 2
  • 26
  • 49
  • 3
    Wnat have you tried so far? What works, what doesn't? –  Sep 13 '13 at 10:37
  • I've rollback your replacement of the question by the solution. Please find [your solution in the revision history](https://stackoverflow.com/revisions/b33fe079-887b-4f53-b75b-57e829d33df8/view-source) and post it as an answer of its own. – Cœur May 14 '18 at 15:31

2 Answers2

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.

ChrisProsser
  • 12,598
  • 6
  • 35
  • 44
  • Yeah this is pretty much what I had come to... but I don't want to have to select a cell (i.e. A2, B1 etc.). I want to be able to just input data in to the cell which is currently active as the Excel macro moves the active cell in to place anyway. Thanks for all your help by the way Chris, it's been really helpful. – ryansin Sep 13 '13 at 16:26
  • @user2696497 I have posted an updated answer here. This now loops through the cell for the column you specify and finds the first available. Let me know if you have any questions. – ChrisProsser Sep 14 '13 at 11:23
  • 1
    That's brilliant, I'll give it a try on Monday morning and let you know how it goes. Thanks again Chris. – ryansin Sep 15 '13 at 16:17
  • Had to make a couple of changes (see amended answer) but sorted now :) Thanks! – ryansin Sep 16 '13 at 11:01
  • @user2696497 Glad you got there in the end. Please could you mark this as the accepted answer if it has resolved the issue. Are you sure that the amened question works correctly? It may just be an indentation issue, but it looks like the update to empty and the row increment are outside of the while loop at the moment, which would theoretically make this get stuck in an infinite loop. – ChrisProsser Sep 16 '13 at 11:33
  • Hi Chris, this has worked for a while, but now I'm having an issue where it isn't checking the space left in the shared folder that is mapped on my computer but rather it is returning the space left in the whole D: drive on one particular server. Any idea what might be causing this? – ryansin Oct 09 '13 at 10:08
  • @user2696497 Hi, I'm not sure what the cause would be, but have you tried using an absolute path rather than a mapped drive e.g. if your server was name svr1 and the path on it was prosserc\misc then set `drive = r'\\svr1\prosserc\misc'` the r infront of the string creates a raw string so that you don't need to escape the backslashes. – ChrisProsser Oct 09 '13 at 10:28
  • Yeah I'd tried using r'\\server\share' but I was having the same issue. There are three shares there and all of the have the same result when tested (around 500GB as that's what is left in the D drive on the server). When I try r'\\server\d$\DFS Shares\Share it tells me that the space left is 0. I thought this might be a permissions issue so gave myself full access to each step but still no joy. – ryansin Oct 09 '13 at 11:13
  • This also only happens for one of the servers. All others work just fine when tested. – ryansin Oct 09 '13 at 11:15
  • @user2696497 sorry, I'm not sure why this would be. As it works okay for me and for other servers that you use it could be something to do with the set-up of the server itself, but this is not my area if expertise. – ChrisProsser Oct 09 '13 at 11:21
0

I think you probably need to break this up into sub problems, have a go at each and post a question for any that you are stuck on, including your attempts in the post. Here are some suggested steps and areas to look into for them:

  1. Work out space remaining on drive. There is a thread here which may be helpful for this.
  2. To write to Excel there is a module named xlwt, which can be downloaded from here. I have also found a brief tutorial for using this here.

EDIT

For Python 3.x I found a port of xlwt which may be worth a try. I found a post here pointing the a github repository here. I could not see an installer, but it should be straight forward to build from source.

You will need to download everything from this github page into a folder and then cd to that directory from the command line and run

Python setup.py install
Community
  • 1
  • 1
ChrisProsser
  • 12,598
  • 6
  • 35
  • 44
  • I tried installing xlwt, but it didn't work. On the installation it mentions it is only meant for Python 2.2 - 2.7, but I'm running 3.3. Thanks for getting back to me btw : – ryansin Sep 13 '13 at 14:02
  • @user2696497 Okay, I have not tried it myself but I found a module that says it supports 3.3: https://xlsxwriter.readthedocs.org/en/latest/. – ChrisProsser Sep 13 '13 at 14:11
  • Thank you I'll give that a go. Currently trying out openpyxl but having some trouble with it – ryansin Sep 13 '13 at 14:37
  • Just had a check but xlsxwriter can't modify existing spreadsheets (which is what I need), it only creates new ones. – ryansin Sep 13 '13 at 14:51
  • Someone has done a port of xlwt to Python 3 which may be worth a try. I found a post here(https://groups.google.com/forum/#!topic/python-excel/cnMjq-9Jp1Q) pointing the a github repository here(https://github.com/hlawrenz/xlwt/tree/py3). I could not see an installer, but it should be straight forward to build from source. I am editing the answer above with details of how to do this. – ChrisProsser Sep 13 '13 at 15:14
  • @user2696497 I have updated the answer, let me know if any problems – ChrisProsser Sep 13 '13 at 15:18
  • I've also updated the question :) is there a way I can get the data into Excel using pywin32? – ryansin Sep 13 '13 at 15:22
  • @user2696497 Here is a thread where it looks like someone has done something similar: http://stackoverflow.com/questions/6337595/python-win32-com-closing-excel-workbook – ChrisProsser Sep 13 '13 at 15:32
  • Fantastic, thanks. I now know how to write to Excel via pywin32, but I don't know how to do it in the active cell without selecting a static cell (if that makes sense?). – ryansin Sep 13 '13 at 16:20
  • @user2696497 Can you explain what you mean by 'in the active cell' as the script opens the spreadsheet, so wouldn't we need to use a reference to set the active cell? Have you tried the code in the other answer below? – ChrisProsser Sep 13 '13 at 16:24
  • The workbook opens on whatever cell it's on for arguments sake we'll say it's on A1. The macro then runs to move the cell down to A2, and this is where I want the data to go. If I set the script to print to A2 then it would just overwrite what was last written every time, however I want to keep adding to the bottom of the list. So the cell would be moved from A1 to A2 by the macro, data would be written into A2. Next time it was run it would be moved down again. See what I mean? – ryansin Sep 13 '13 at 16:33