如何以编程方式返回关键字的位置(行和列)

时间:2018-06-25 22:06:42

标签: python excel

我正在尝试使用python自动分析数百个excel文件。目前,我可以打开,写入和保存文件,但需要在包含关键字的单元格中插入计算。我正在使用python 2.7,这是我苦苦挣扎的代码的片段:

def run_analysis():
    excel = Dispatch('Excel.Application')
    excel.DisplayAlerts = False
    keyword = "Total Traffic"
    x = 0
    t = data_file_location_list

    while x < len(t):
        #for files in data_file_location_list:
        wb = excel.Workbooks.Open(t[x].root_dir + "\\" + t[x].file_name)
        ws = wb.Sheets('Bandwidth Over Time')

        keyword_range = #here is where I am stuck

        ws.Range(keyword_range).Value = 'write something'
        wb.SaveAs(Filename=str(t[x].root_dir + "\\" + t[x].file_name))
        wb.Close()
        excel.Quit()
        print x
        x += 1

1 个答案:

答案 0 :(得分:0)

以防万一有人在执行此操作,我弄清楚了并认为我会分享答案。我想出了FindCell函数,尽管可能有一种更为优雅的方法。

def run_analysis():
    excel = Dispatch('Excel.Application')
    excel.DisplayAlerts = False
    x = 0
    t = data_file_location_list

    while x < len(t):
        # MATCHES ROW AND COL INPUT FOR CELL ADDRESS OUTPUT
        def FindCell(descriptor, banner):
            return(ws.Cells(excel.WorksheetFunction.Match(descriptor, ws.Range("B:B"), 0), 
                               excel.WorksheetFunction.Match(banner, ws.Range("A:A"), 0)).Address)

        try:
            print 'opening: ' + t[x].root_dir + "\\" + t[x].file_name

            wb                                 = excel.Workbooks.Open(t[x].root_dir + "\\" + t[x].file_name)
            ws                                 = wb.Sheets('Bandwidth Over Time')  

            #find the cell below the cell containing "Total Traffic"
            total_traffic_calc_range           = FindCell("Traffic", 'Bandwidth Over Time')
            total_traffic_calc_range_delimiter = int(total_traffic_calc_range.strip('$A$'))
            total_traffic_equation_cell        = "C" + str(total_traffic_calc_range_delimiter)

            #add the equations for calculation
            ws.Range(total_traffic_equation_cell).Value = '=Sum(' + 'B' + str(
                    total_traffic_calc_range_delimiter + 1) + ':B' + str(
                            total_throughput_calc_range_delimiter - 2) + ')'

            wb.SaveAs(Filename = str(t[x].root_dir + "\\" + t[x].file_name))

        except Exception as e:
            print e

        finally:
            wb.Close()
            excel.Quit()
            print x
            x += 1