Writing to an Excel spreadsheet

后端 未结 12 1837
不知归路
不知归路 2020-11-22 04:39

I am new to Python. I need to write some data from my program to a spreadsheet. I\'ve searched online and there seem to be many packages available (xlwt, XlsXcessive, openpy

相关标签:
12条回答
  • 2020-11-22 05:06

    Use DataFrame.to_excel from pandas. Pandas allows you to represent your data in functionally rich datastructures and will let you read in excel files as well.

    You will first have to convert your data into a DataFrame and then save it into an excel file like so:

    In [1]: from pandas import DataFrame
    In [2]: l1 = [1,2,3,4]
    In [3]: l2 = [1,2,3,4]
    In [3]: df = DataFrame({'Stimulus Time': l1, 'Reaction Time': l2})
    In [4]: df
    Out[4]: 
       Reaction Time  Stimulus Time
    0              1              1
    1              2              2
    2              3              3
    3              4              4
    
    In [5]: df.to_excel('test.xlsx', sheet_name='sheet1', index=False)
    

    and the excel file that comes out looks like this:

    enter image description here

    Note that both lists need to be of equal length else pandas will complain. To solve this, replace all missing values with None.

    0 讨论(0)
  • 2020-11-22 05:14
    import xlsxwriter
    
    
    # Create an new Excel file and add a worksheet.
    workbook = xlsxwriter.Workbook('demo.xlsx')
    worksheet = workbook.add_worksheet()
    
    # Widen the first column to make the text clearer.
    worksheet.set_column('A:A', 20)
    
    # Add a bold format to use to highlight cells.
    bold = workbook.add_format({'bold': True})
    
    # Write some simple text.
    worksheet.write('A1', 'Hello')
    
    # Text with formatting.
    worksheet.write('A2', 'World', bold)
    
    # Write some numbers, with row/column notation.
    worksheet.write(2, 0, 123)
    worksheet.write(3, 0, 123.456)
    
    # Insert an image.
    worksheet.insert_image('B5', 'logo.png')
    
    workbook.close()
    
    0 讨论(0)
  • 2020-11-22 05:15

    The xlsxwriter library is great for creating .xlsx files. The following snippet generates an .xlsx file from a list of dicts while stating the order and the displayed names:

    from xlsxwriter import Workbook
    
    
    def create_xlsx_file(file_path: str, headers: dict, items: list):
        with Workbook(file_path) as workbook:
            worksheet = workbook.add_worksheet()
            worksheet.write_row(row=0, col=0, data=headers.values())
            header_keys = list(headers.keys())
            for index, item in enumerate(items):
                row = map(lambda field_id: item.get(field_id, ''), header_keys)
                worksheet.write_row(row=index + 1, col=0, data=row)
    
    
    headers = {
        'id': 'User Id',
        'name': 'Full Name',
        'rating': 'Rating',
    }
    
    items = [
        {'id': 1, 'name': "Ilir Meta", 'rating': 0.06},
        {'id': 2, 'name': "Abdelmadjid Tebboune", 'rating': 4.0},
        {'id': 3, 'name': "Alexander Lukashenko", 'rating': 3.1},
        {'id': 4, 'name': "Miguel Díaz-Canel", 'rating': 0.32}
    ]
    
    create_xlsx_file("my-xlsx-file.xlsx", headers, items)
    


    0 讨论(0)
  • 2020-11-22 05:17

    OpenPyxl is quite a nice library, built to read/write Excel 2010 xlsx/xlsm files:

    https://openpyxl.readthedocs.io/en/stable

    The other answer, referring to it is using the deperciated function (get_sheet_by_name). This is how to do it without it:

    import openpyxl
    
    wbkName = 'New.xlsx'        #The file should be created before running the code.
    wbk = openpyxl.load_workbook(wbkName)
    wks = wbk['test1']
    someValue = 1337
    wks.cell(row=10, column=1).value = someValue
    wbk.save(wbkName)
    wbk.close
    
    0 讨论(0)
  • 2020-11-22 05:19
    • xlrd/xlwt (standard): Python does not have this functionality in it's standard library, but I think of xlrd/xlwt as the "standard" way to read and write excel files. It is fairly easy to make a workbook, add sheets, write data/formulas, and format cells. If you need all of these things, you may have the most success with this library. I think you could choose openpyxl instead and it would be quite similar, but I have not used it.

      To format cells with xlwt, define a XFStyle and include the style when you write to a sheet. Here is an example with many number formats. See example code below.

    • Tablib (powerful, intuitive): Tablib is a more powerful yet intuitive library for working with tabular data. It can write excel workbooks with multiple sheets as well as other formats, such as csv, json, and yaml. If you don't need formatted cells (like background color), you will do yourself a favor to use this library, which will get you farther in the long run.

    • csv (easy): Files on your computer are either text or binary. Text files are just characters, including special ones like newlines and tabs, and can be easily opened anywhere (e.g. notepad, your web browser, or Office products). A csv file is a text file that is formatted in a certain way: each line is a list of values, separated by commas. Python programs can easily read and write text, so a csv file is the easiest and fastest way to export data from your python program into excel (or another python program).

      Excel files are binary and require special libraries that know the file format, which is why you need an additional library for python, or a special program like Microsoft Excel, Gnumeric, or LibreOffice, to read/write them.


    import xlwt
    
    style = xlwt.XFStyle()
    style.num_format_str = '0.00E+00'
    
    ...
    
    for i,n in enumerate(list1):
        sheet1.write(i, 0, n, fmt)
    
    0 讨论(0)
  • 2020-11-22 05:21

    I surveyed a few Excel modules for Python, and found openpyxl to be the best.

    The free book Automate the Boring Stuff with Python has a chapter on openpyxl with more details or you can check the Read the Docs site. You won't need Office or Excel installed in order to use openpyxl.

    Your program would look something like this:

    import openpyxl
    wb = openpyxl.load_workbook('example.xlsx')
    sheet = wb.get_sheet_by_name('Sheet1')
    
    stimulusTimes = [1, 2, 3]
    reactionTimes = [2.3, 5.1, 7.0]
    
    for i in range(len(stimulusTimes)):
        sheet['A' + str(i + 6)].value = stimulusTimes[i]
        sheet['B' + str(i + 6)].value = reactionTimes[i]
    
    wb.save('example.xlsx')
    
    0 讨论(0)
提交回复
热议问题