Question

I have the following scenario to use:

There exists one template excel file with lots of column, each of them has column name. I have some datas stored in MySQL, and I want to insert data into appropriate column. I know MySQLdb could be used to link MySQL in python, but any good way to do with EXCEL operation?

it's different than csv so I am not sure any good solution. Thanks for your help.

Was it helpful?

Solution

I think the following steps will do this work:

  1. open MS excel.
  2. read column names in excel file
  3. write related data based on your data in MySQL.

For step1, may get help from xlrd

For step2, please reference the following code:

    # read excel and get appropriate sheet
    rb = xlrd.open_workbook(filename, on_demand=True, formatting_info=True)
    my_sheet = rb.sheet_by_name(u'template name')

    # get column names in item_list        
    item_list = my_sheet.row_values(1)
    nrows = my_sheet.rows
    ncolumns = my_sheet.columns
    key_index = item_list.index('A')
    value_index = item_list.index('B') # of course 'C' and 'D' if needed

For step3, may use index to get value in each row

    wb = copy(rb)
    ws = wb.get_sheet(i) # get related sheet to write
    for row in nrows:
        key = my_sheet[row][key_index]
        ....

Please see my application if needed

OTHER TIPS

from http://www.python-excel.org/

There are python packages available to work with Excel files that will run on any Python platform and that do not require either Windows or Excel to be used. They are fast, reliable and open source:

  • xlrd: This package is for reading data and formatting information from Excel files.
  • xlwt: This package is for writing data and formatting information to Excel files.
  • xlutils: This package collects utilities that require both xlrd and xlwt, including the ability to copy and modify or filter existing excel files.

There is a Google Group dedicated to working with Excel files in Python, including the libraries listed above along with manipulating the Excel application via COM.

Google is usually a better source than StackOverflow for this sort of things...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top