简体   繁体   English

Python MS Excel读写

[英]Python MS Excel Read and Write

I have the following scenario to use: 我可以使用以下方案:

There exists one template excel file with lots of column, each of them has column name. 存在一个具有许多列的模板excel文件,每个文件都有列名称。 I have some datas stored in MySQL, and I want to insert data into appropriate column. 我有一些数据存储在MySQL中,我想将数据插入适当的列中。 I know MySQLdb could be used to link MySQL in python, but any good way to do with EXCEL operation? 我知道MySQLdb可以用来在python中链接MySQL,但是与EXCEL操作有什么好的方法吗?

it's different than csv so I am not sure any good solution. 它与csv不同,因此我不确定是否有任何好的解决方案。 Thanks for your help. 谢谢你的帮助。

from http://www.python-excel.org/ 来自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. 有可用于Excel文件的python软件包,这些软件包可在任何Python平台上运行,并且不需要使用Windows或Excel。 They are fast, reliable and open source: 它们是快速,可靠和开源的:

  • xlrd : This package is for reading data and formatting information from Excel files. xlrd :此软件包用于从Excel文件读取数据和格式化信息。
  • xlwt : This package is for writing data and formatting information to Excel files. xlwt :此软件包用于将数据写入格式和格式信息到Excel文件。
  • xlutils : This package collects utilities that require both xlrd and xlwt, including the ability to copy and modify or filter existing excel files. xlutils :此软件包收集同时需要xlrd和xlwt的实用程序,包括复制和修改或过滤现有excel文件的功能。

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 Group致力于使用Python处理Excel文件,包括上面列出的库以及通过COM操纵Excel应用程序。

Google is usually a better source than StackOverflow for this sort of things... 对于这类事情,Google通常比StackOverflow更好。

I think the following steps will do this work: 我认为以下步骤将完成这项工作:

  1. open MS excel. 打开MS excel。
  2. read column names in excel file 读取Excel文件中的列名
  3. write related data based on your data in MySQL. 根据您在MySQL中的数据编写相关数据。

For step1, may get help from xlrd 对于步骤1,可能会从xlrd获得帮助

For step2, please reference the following code: 对于步骤2,请参考以下代码:

    # 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 对于步骤3,可以使用索引获取每一行的值

    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 如有需要,请参阅我的申请

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM