Имя листа excel python

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    The openpyxl library is widely used to handle excel files using Python. Often when dealing with excel files one might have noticed multiple sheets. The sheets are normally mentioned in the bottom left corner of the screen. One can install this library by running the following command.

    pip install openpyxl

    In this article, we will be seeing how to get the names of these sheets and display them using openpyxl.

    The file we will be using here is named Example.xlsx and has the following sheets. 

    How to get sheet names using openpyxl in Python

    Python Codde to get sheet names using Openpyxl

    First, we need to import the openpyxl library. After this, we will load our excel sheet Example.xlsx. Then by using the function sheetnames we can get a list of names of all the sub sheets that are present in the main sheet.

    Python3

    import openpyxl as xl

    excel_file = "Example.xlsx"

    wb = xl.load_workbook(excel_file)

    print(wb.sheetnames)

    print("Active sheet: ", wb.active)

    wb._active_sheet_index = 4

    sheet = wb.active

    print("Active sheet: ", wb.active)

    Output:

    ['sales_q1', 'sales_q3', 'sales_q4', 'sales_q2', 'sales_monthly']
    Active sheet:  <Worksheet "sales_q1">
    Active sheet:  <Worksheet "sales_monthly">

    Like Article

    Save Article

    I have a moderately large xlsx file (around 14 MB) and OpenOffice hangs trying to open it. I was trying to use openpyxl to read the content, following this tutorial. The code snippet is as follows:

     from openpyxl import load_workbook
     wb = load_workbook(filename = 'large_file.xlsx', use_iterators = True)
     ws = wb.get_sheet_by_name(name = 'big_data') 
    

    The problem is, I don’t know the sheet name, and Sheet1/Sheet2.. etc. didn’t work (returned NoneType object). I could not find a documentation telling me How to get the sheet names for an xlsx files using openpyxl. Can anyone help me?

    asked May 7, 2014 at 20:36

    rivu's user avatar

    Use the sheetnames property:

    sheetnames

    Returns the list of the names of worksheets in this workbook.

    Names are returned in the worksheets order.

    Type: list of strings

    print (wb.sheetnames)
    

    You can also get worksheet objects from wb.worksheets:

    ws = wb.worksheets[0]
    

    Petter's user avatar

    Petter

    36.6k6 gold badges46 silver badges62 bronze badges

    answered May 7, 2014 at 20:48

    alecxe's user avatar

    alecxealecxe

    458k119 gold badges1069 silver badges1182 bronze badges

    5

    As a complement to the other answers, for a particular worksheet, you can also use cf documentation in the constructor parameters:

    ws.title
    

    answered Feb 18, 2022 at 16:25

    lalebarde's user avatar

    lalebardelalebarde

    1,6561 gold badge21 silver badges35 bronze badges

    python 3.x
    for get sheet name you must use attribute

    g_sheet=wb.sheetnames
    

    return by list

    for i in g_sheet:
        print(i)
    

    **shoose any name **

    ws=wb[g_sheet[0]]
    

    or ws=wb[any name]
    suppose name sheet is paster

    ws=wb["paster"]
    

    answered Aug 3, 2019 at 20:08

    ismail's user avatar

    ismailismail

    1792 silver badges6 bronze badges

    As mentioned the earlier answer
    you can get the list of sheet names
    by using the ws.sheetnames

    But if you know the sheet names you can get that worksheet object by

    ws.get_sheet_by_name("YOUR_SHEET_NAME")
    

    Another way of doing this is as mentioned in earlier answer

    ws['YOUR_SHEET_NAME']
    

    answered Jun 7, 2019 at 1:59

    Kamaraj's user avatar

    KamarajKamaraj

    631 silver badge8 bronze badges

    for worksheet in workbook:
        print(worksheet.name)
    

    answered Nov 17, 2022 at 20:58

    lulu's user avatar

    Working with Excel files in Python is not that much hard as you might think. In this tutorial, we are going to learn how to create, read and modify .xlsx files using python.

    Introduction

    Xlsx files are the most widely used documents in the technology field. Data Scientists uses spreadsheets more than anyone else in the world and obivously they don’t do it manually.

    We will need a module called openpyxl which is used to read, create and work with .xlsx files in python. There are some other modules like xlsxwriter, xlrd, xlwt, etc., but, they don’t have methods for performing all the operations on excel files. To install the openpyxl module run the following command in command line:

    pip install openpyxl

    Let’s see what all operations one can perform using the openpyxl module after importing the module in our code, which is simple:

    import openpyxl

    Once we have imported the module in our code, all we have to do is use various methods of the module to rad, write and create .xlsx files.


    Creating New .xlsx File

    In this program, we are going to create a new .xlsx file.

    import openpyxl
    
    ## CREATING XLSX FILE
    
    ## initializing the xlsx
    xlsx = openpyxl.Workbook()
    
    ## creating an active sheet to enter data
    sheet = xlsx.active
    
    ## entering data into the A1 and B1 cells in the sheet
    sheet['A1'] = 'Studytonight'
    sheet['B1'] = 'A Programming Site'
    
    ## saving the xlsx file using 'save' method
    xlsx.save('sample.xlsx')

    The above program creates an .xlsx file with the name sample.xlsx in the present working directory.

    Creating Xlsx File using openpyxl python module


    Writing to a Cell

    There are to ways to write to a cell. The first method is the one which we used in the program above and the second method is using the cell() method by passing the row and column numbers.

    Let’s see how the second way works:

    import openpyxl
    
    ## initializing the xlsx
    xlsx = openpyxl.Workbook()
    
    ## creating an active sheet to enter data
    sheet = xlsx.active
    
    ## entering data into the cells using 1st method
    sheet['A1'] = 'Studytonight'
    sheet['B2'] = 'Cell B2'
    
    ## entering data into the cells using 2nd method
    sheet.cell(row = 1, column = 2).value = 'A Programming Site'
    sheet.cell(row = 2, column = 1).value = "B1"
    
    ## saving the xlsx file using 'save' method
    xlsx.save('write_to_cell.xlsx')

    adding cell data to Xlsx File using openpyxl python module

    In the second method above, we are getting the cell with the row and column values. After getting the cell, we are assigning a value to it using the value variable.


    Appending Data to a .xlsx file

    The append() method is used to append the data to any cell. Here is an example:

    import openpyxl
    
    ## initializing the xlsx
    xlsx = openpyxl.Workbook()
    
    ## creating an active sheet to enter data
    sheet = xlsx.active
    
    ## creating data to append
    data = [
             [1, 2, 3],
             [4, 5, 6],
             [7, 8, 9],
             [10, 11, 12]
           ]
    
    ## appending row by row to the sheet
    for row in data:
        ## append method is used to append the data to a cell
        sheet.append(row)
    
    ## saving the xlsx file using 'save' method
    xlsx.save('appending.xlsx')

    Appending data to .xlsx file using openpyxl module python

    Using the above program, we have appended 4 rows and 3 column values in our .xlsx file. You can also use tuples or any iteratable object instead of lists.


    Reading Data from a Cell

    We are now going to learn how to read data from a cell in a xlsx file. We will use the previously created .xlsx file to read data from the cell.

    import openpyxl
    
    ## opening the previously created xlsx file using 'load_workbook()' method
    xlsx = openpyxl.load_workbook('sample.xlsx')
    
    ## getting the sheet to active
    sheet = xlsx.active
    
    ## getting the reference of the cells which we want to get the data from
    name = sheet['A1']
    tag = sheet.cell(row = 1, column = 2)
    
    ## printing the values of cells
    print(name.value)
    print(tag.value)

    Output of above Program:

    Studytonight
    A Programming Site
    

    Reading Data from Multiple Cells

    Now we are going to use the appending.xlsx file to read data. It contains numeric values from 1 to 12 saved in the cells in form of 4 rows and 3 columns.

    import openpyxl
    
    ## opening the previously created xlsx file using 'load_workbook()' method
    xlsx = openpyxl.load_workbook('appending.xlsx')
    
    ## getting the sheet to active
    sheet = xlsx.active
    
    ## getting the reference of the cells which we want to get the data from
    values = sheet['A1' : 'C4']
    
    ## printing the values of cells
    for c1, c2, c3 in values:
    print("{} {} {}".format(c1.value, c2.value, c3.value))

    Output of above Program:

    1 2 3
    4 5 6
    7 8 9
    10 11 12

    Slicing method applied on cells returns a tuple containing each row as a tuple. And we can print all the cell’s data using a loop.


    Getting Dimensions of an .xlsx Sheet

    Getting the dimensions of an .xlsx sheet is also possible and super-easy using the dimensions method.

    import openpyxl
    
    ## opening the previously created xlsx file using 'load_workbook()' method
    xlsx = openpyxl.load_workbook('appending.xlsx')
    
    ## getting the sheet to active
    sheet = xlsx.active
    
    ## getting the reference of the cells which we want to get the data from
    dimensions = sheet.dimensions
    
    ## printing the dimensions of the sheet
    print(dimensions)

    Output of above Program:

    A1:C4

    The output of the dimensions method is the range of the sheet from which cell to which cell the data is present.


    Getting Data from Rows of .xlsx File

    We can also get data from all the rows of an xlsx file by using the rows method.

    import openpyxl
    
    ## opening the previously created xlsx file using 'load_workbook()' method
    xlsx = openpyxl.load_workbook('appending.xlsx')
    
    ## getting the sheet to active
    sheet = xlsx.active
    
    ## getting the reference of the cells which we want to get the data from
    rows = sheet.rows
    
    ## printing the values of cells using rows
    for row in rows:
        for cell in row:
            print(cell.value, end = ' ')
    
        print("n")

    Output of above Program:

    1 2 3 
    4 5 6 
    7 8 9 
    10 11 12

    rows method returns a generator which contains all rows of the sheet.


    Getting Data from Columns of .xlsx File

    We can get data from all the columns of an xlsx file by using the columns method.

    import openpyxl
    
    ## opening the previously created xlsx file using 'load_workbook()' method
    xlsx = openpyxl.load_workbook('appending.xlsx')
    
    ## getting the sheet to active
    sheet = xlsx.active
    
    ## getting the reference of the cells which we want to get the data from
    columns = sheet.columns
    
    ## printing the values of cells using rows
    for column in columns:
        for cell in column:
            print(cell.value, end = ' ')
        print("n")

    Output of above Program:

    1 4 7 10 
    2 5 8 11 
    3 6 9 12

    columns method returns a generator which contains all the columns of the sheet.


    Working with Excel Sheets

    In this section we will see how we can create more sheets, get name of sheets and even change the name of any given sheet etc.

    1. Changing the name of an Excel Sheet

    We can also change the name of a given excel sheet using the title variable. Let’s see an example:

    import openpyxl
    
    ## initializing the xlsx
    xlsx = openpyxl.Workbook()
    
    ## creating an active sheet to enter data
    sheet = xlsx.active
    
    ## entering data into the A1 and B1 cells in the sheet
    sheet['A1'] = 'Studytonight'
    sheet['B1'] = 'A Programming Site'
    
    ## setting the title for the sheet
    sheet.title = "Sample"
    
    ## saving the xlsx file using 'save' method
    xlsx.save('sample.xlsx')

    change sheet name using openpyxl module in python


    2. Getting Excel Sheet name

    Getting the names of all the sheets present in xlsx file is super easy using the openpyxl module. We can use the method called get_sheet_names() to get names of all the sheets present in the excel file.

    import openpyxl
    
    ## initializing the xlsx
    xlsx = openpyxl.load_workbook('sample.xlsx')
    
    ## getting all sheet names
    names = xlsx.get_sheet_names()
    
    print(names)

    Output of above Program:

    ['Sample']
    

    3. Creating more than one Sheet in an Excel File

    When creating our first xlsx file, we only created one sheet. Let’s see how to create multiple sheets and give names to them.

    import openpyxl
    
    ## initializing the xlsx
    xlsx = openpyxl.Workbook()
    
    ## creating sheets
    xlsx.create_sheet("School")
    xlsx.create_sheet("College")
    xlsx.create_sheet("University")
    
    ## saving the xlsx file using 'save' method
    xlsx.save('multiple_sheets.xlsx')

    Multiple Sheets

    As you can see in the snapshot above that a new excel file is created with 3 new sheets with different names provided by us in the program.


    4. Adding Data to Multiple Sheets

    Entering data into different sheets present in xlsx file can also be done easily. In the program below, we will get the sheets by their names individually or all at once as we have done above. Let’s see how to get sheets using their name and enter data into them.

    We will use previously created xlsx file called multiple_sheets.xlsx to enter the data into sheets.

    import openpyxl
    
    ## initializing the xlsx
    xlsx = openpyxl.Workbook()
    
    ## creating sheets
    xlsx.create_sheet("School")
    xlsx.create_sheet("College")
    xlsx.create_sheet("University")
    
    ## getting sheet by it's name
    school = xlsx.get_sheet_by_name("School")
    school['A1'] = 1
    
    ## getting sheet by it's name
    college = xlsx.get_sheet_by_name("College")
    college['A1'] = 2
    
    ## getting sheet by it's name
    university = xlsx.get_sheet_by_name("University")
    university['A1'] = 3
    
    ## saving the xlsx file using 'save' method
    xlsx.save('multiple_sheets.xlsx')

    Creating multiple sheets in excel file using openpyxl python module

    We can’t modify the existing xlsx file using the openpyxl module but we can read data from it.


    Conclusion

    We have seen different methods which can be used while working with xlsx files using Python. If you want to explore more methods available in the openpyxl module, then you can try them using the dir() method to get information about all methods of openpyxl module.

    You can also see other modules like xlsxwriter, xlrd, xlwt, etc., for more functionalities. If you have already used any of these modules, do share your experience with us through comments section.

    You may also like:

    • Converting Xlsx file To CSV file using Python
    • How to copy elements from one list to another in Python
    • Calculate Time taken by a Program to Execute in Python
    • Dlib 68 points Face landmark Detection with OpenCV and Python

    Электронные таблицы Excel — это интуитивно понятный и удобный способ манипулирования большими наборами данных без какой-либо предварительной технической подготовки. По этому, это один из форматов, с которым, в какой-то момент времени, вам придется иметь дело. Часто будут стоять задачи по извлечению каких-то данных из базы данных или файла логов в электронную таблицу Excel, или наоборот, преобразовывать электронную таблицу Excel в какую-либо более удобную программную форму, примеров этому масса.

    Модуль openpyxl — это библиотека Python для чтения/записи форматов Office Open XML (файлов Excel 2010) с расширениями xlsx/xlsm/xltx/xltm.

    Установка модуля openpyxl в виртуальное окружение.

    Модуль openpyxl размещен на PyPI, поэтому установка относительно проста.

    # создаем виртуальное окружение, если нет
    $ python3 -m venv .venv --prompt VirtualEnv
    # активируем виртуальное окружение 
    $ source .venv/bin/activate
    # ставим модуль openpyxl
    (VirtualEnv):~$ python3 -m pip install -U openpyxl
    

    Основы работы с файлами Microsoft Excel на Python.

    • Создание книги Excel.
      • Новый рабочий лист книги Excel.
      • Копирование рабочего листа книги Excel.
      • Удаление рабочего листа книги Excel.
    • Доступ к ячейке электронной таблицы и ее значению.
    • Доступ к диапазону ячеек листа электронной таблицы.
    • Получение только значений ячеек листа.
    • Добавление данных в ячейки списком.
    • Сохранение созданной книги в файл Excel.
      • Сохранение данных книги в виде потока.
    • Загрузка документа XLSX из файла.

    Создание книги Excel.

    Чтобы начать работу с модулем openpyxl, нет необходимости создавать файл электронной таблицы в файловой системе. Нужно просто импортировать класс Workbook и создать его экземпляр. Рабочая книга всегда создается как минимум с одним рабочим листом, его можно получить, используя свойство Workbook.active:

    >>> from openpyxl import Workbook
    # создаем книгу 
    >>> wb = Workbook()
    # делаем единственный лист активным 
    >>> ws = wb.active
    

    Новый рабочий лист книги Excel.

    Новые рабочие листы можно создавать, используя метод Workbook.create_sheet():

    # вставить рабочий лист в конец (по умолчанию)
    >>> ws1 = wb.create_sheet("Mysheet")
    # вставить рабочий лист в первую позицию
    >>> ws2 = wb.create_sheet("Mysheet", 0)
    # вставить рабочий лист в предпоследнюю позицию
    >>> ws3 = wb.create_sheet("Mysheet", -1)
    

    Листам автоматически присваивается имя при создании. Они нумеруются последовательно (Sheet, Sheet1, Sheet2, …). Эти имена можно изменить в любое время с помощью свойства Worksheet.title:

    Цвет фона вкладки с этим заголовком по умолчанию белый. Можно изменить этот цвет, указав цветовой код RRGGBB для атрибута листа Worksheet.sheet_properties.tabColor:

    >>> ws.sheet_properties.tabColor = "1072BA"
    

    Рабочий лист можно получить, используя его имя в качестве ключа экземпляра созданной книги Excel:

    Что бы просмотреть имена всех рабочих листов книги, необходимо использовать атрибут Workbook.sheetname. Также можно итерироваться по рабочим листам книги Excel.

    >>> wb.sheetnames
    # ['Mysheet1', 'NewPage', 'Mysheet2', 'Mysheet']
    
    >>> for sheet in wb:
    ...     print(sheet.title)
    # Mysheet1
    # NewPage
    # Mysheet2
    # Mysheet
    

    Копирование рабочего листа книги Excel.

    Для создания копии рабочих листов в одной книге, необходимо воспользоваться методом Workbook.copy_worksheet():

    >>> source_page = wb.active
    >>> target_page = wb.copy_worksheet(source_page)
    

    Примечание. Копируются только ячейки (значения, стили, гиперссылки и комментарии) и определенные атрибуты рабочего листа (размеры, формат и свойства). Все остальные атрибуты книги/листа не копируются, например, изображения или диаграммы.

    Поддерживается возможность копирования рабочих листов между книгами. Нельзя скопировать рабочий лист, если рабочая книга открыта в режиме только для чтения или только для записи.

    Удаление рабочего листа книги Excel.

    Очевидно, что встает необходимость удалить лист электронной таблицы, который уже существует. Модуль openpyxl дает возможность удалить лист по его имени. Следовательно, сначала необходимо выяснить, какие листы присутствуют в книге, а потом удалить ненужный. За удаление листов книги отвечает метод Workbook.remove().

    Смотрим пример:

    # выясним, названия листов присутствуют в книге
    >>> name_list = wb.sheetnames
    >>> name_list
    # ['Mysheet1', 'NewPage', 'Mysheet2', 'Mysheet', 'Mysheet1 Copy']
    
    # допустим, что нам не нужны первый и последний
    # удаляем первый лист по его имени с проверкой 
    # существования такого имени в книге
    >>> if 'Mysheet1' in wb.sheetnames:
            # Если лист с именем `Mysheet1` присутствует
            # в списке листов экземпляра книги, то удаляем
    ...     wb.remove(wb['Mysheet1'])
    ...
    >>> wb.sheetnames
    # ['NewPage', 'Mysheet2', 'Mysheet', 'Mysheet1 Copy']
    
    # удаляем последний лист через оператор
    #  `del`, имя листа извлечем по индексу 
    # полученного списка `name_list`
    >>> del wb[name_list[-1]]
    >>> wb.sheetnames
    # ['NewPage', 'Mysheet2', 'Mysheet']
    

    Доступ к ячейке и ее значению.

    После того как выбран рабочий лист, можно начинать изменять содержимое ячеек. К ячейкам можно обращаться непосредственно как к ключам рабочего листа, например ws['A4']. Это вернет ячейку на A4 или создаст ее, если она еще не существует. Значения могут быть присвоены напрямую:

    >>> ws['A4'] = 5
    >>> ws['A4']
    # <Cell 'NewPage'.A4>
    >>> ws['A4'].value
    # 5
    >>> ws['A4'].column
    # 1
    >>> ws['A4'].row
    # 4
    

    Если объект ячейки присвоить переменной, то этой переменной, также можно присваивать значение:

    >>> c = ws['A4']
    >>> c.value = c.value * 2
    >>> c.value
    # 10
    

    Существует также метод Worksheet.cell(). Он обеспечивает доступ к ячейкам с непосредственным указанием значений строк и столбцов:

    >>> d = ws.cell(row=4, column=2, value=10)
    >>> d
    # <Cell 'NewPage'.B4>
    >>> d.value = 3.14
    >>> print(d.value)
    # 3.14
    

    Примечание. При создании рабочего листа в памяти, он не содержит ячеек. Ячейки создаются при первом доступе к ним.

    Важно! Из-за такого поведения, простой перебор ячеек в цикле, создаст объекты этих ячеек в памяти, даже если не присваивать им значения.

    Не запускайте этот пример, поверьте на слово:

    # создаст в памяти 100x100=10000 пустых объектов  
    # ячеек, просто так израсходовав оперативную память.
    >>> for x in range(1,101):
    ...        for y in range(1,101):
    ...            ws.cell(row=x, column=y)
    

    Доступ к диапазону ячеек листа электронной таблицы.

    Диапазон с ячейками активного листа электронной таблицы можно получить с помощью простых срезов. Эти срезы будут возвращать итераторы объектов ячеек.

    >>> cell_range = ws['A1':'C2']
    >>> cell_range
    # ((<Cell 'NewPage'.A1>, <Cell 'NewPage'.B1>, <Cell 'NewPage'.C1>), 
    # (<Cell 'NewPage'.A2>, <Cell 'NewPage'.B2>, <Cell 'NewPage'.C2>))
    

    Аналогично можно получить диапазоны имеющихся строк или столбцов на листе:

    # Все доступные ячейки в колонке `C`
    >>> colC = ws['C']
    # Все доступные ячейки в диапазоне колонок `C:D`
    >>> col_range = ws['C:D']
    # Все доступные ячейки в строке 10
    >>> row10 = ws[10]
    # Все доступные ячейки в диапазоне строк `5:10`
    >>> row_range = ws[5:10]
    

    Можно также использовать метод Worksheet.iter_rows():

    >>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
    ...    for cell in row:
    ...        print(cell)
    # <Cell Sheet1.A1>
    # <Cell Sheet1.B1>
    # <Cell Sheet1.C1>
    # <Cell Sheet1.A2>
    # <Cell Sheet1.B2>
    # <Cell Sheet1.C2>
    

    Точно так же метод Worksheet.iter_cols() будет возвращать столбцы:

    >>> for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
    ...     for cell in col:
    ...         print(cell)
    # <Cell Sheet1.A1>
    # <Cell Sheet1.A2>
    # <Cell Sheet1.B1>
    # <Cell Sheet1.B2>
    # <Cell Sheet1.C1>
    # <Cell Sheet1.C2>
    

    Примечание. Из соображений производительности метод Worksheet.iter_cols() недоступен в режиме только для чтения.

    Если необходимо перебрать все строки или столбцы файла, то можно использовать свойство Worksheet.rows:

    >>> ws = wb.active
    >>> ws['C9'] = 'hello world'
    >>> tuple(ws.rows)
    # ((<Cell Sheet.A1>, <Cell Sheet.B1>, <Cell Sheet.C1>),
    # (<Cell Sheet.A2>, <Cell Sheet.B2>, <Cell Sheet.C2>),
    # (<Cell Sheet.A3>, <Cell Sheet.B3>, <Cell Sheet.C3>),
    # ...
    # (<Cell Sheet.A7>, <Cell Sheet.B7>, <Cell Sheet.C7>),
    # (<Cell Sheet.A8>, <Cell Sheet.B8>, <Cell Sheet.C8>),
    # (<Cell Sheet.A9>, <Cell Sheet.B9>, <Cell Sheet.C9>))
    

    или свойство Worksheet.columns:

    >>> tuple(ws.columns)
    # ((<Cell Sheet.A1>,
    # <Cell Sheet.A2>,
    # ...
    # <Cell Sheet.B8>,
    # <Cell Sheet.B9>),
    # (<Cell Sheet.C1>,
    # <Cell Sheet.C2>,
    # ...
    # <Cell Sheet.C8>,
    # <Cell Sheet.C9>))
    

    Примечание. Из соображений производительности свойство Worksheet.columns недоступно в режиме только для чтения.

    Получение только значений ячеек активного листа.

    Если просто нужны значения из рабочего листа, то можно использовать свойство активного листа Worksheet.values. Это свойство перебирает все строки на листе, но возвращает только значения ячеек:

    for row in ws.values:
       for value in row:
         print(value)
    

    Для возврата только значения ячейки, методы Worksheet.iter_rows() и Worksheet.iter_cols(), представленные выше, могут принимать аргумент values_only:

    >>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2, values_only=True):
    ...   print(row)
    # (None, None, None)
    # (None, None, None)
    

    Добавление данных в ячейки листа списком.

    Модуль openpyxl дает возможность супер просто и удобно добавлять данные в конец листа электронной таблицы. Такое удобство обеспечивается методом объекта листа Worksheet.append(iterable), где аргумент iterable — это любой итерируемый объект (список, кортеж и т.д.). Такое поведение позволяет, без костылей, переносить в электронную таблицу данные из других источников, например CSV файлы, таблицы баз данных, дата-фреймы из Pandas и т.д.

    Метод Worksheet.append() добавляет группу значений в последнюю строку, которая не содержит данных.

    • Если это список: все значения добавляются по порядку, начиная с первого столбца.
    • Если это словарь: значения присваиваются столбцам, обозначенным ключами (цифрами или буквами).

    Варианты использования:

    • добавление списка: .append([‘ячейка A1’, ‘ячейка B1’, ‘ячейка C1’])
    • добавление словаря:
      • вариант 1: .append({‘A’ : ‘ячейка A1’, ‘C’ : ‘ячейка C1’}), в качестве ключей используются буквы столбцов.
      • вариант 2: .append({1 : ‘ячейка A1’, 3 : ‘ячейка C1’}), в качестве ключей используются цифры столбцов.

    Пример добавление данных из списка:

    # существующие листы рабочей книги
    >>> wb.sheetnames
    # ['NewPage', 'Mysheet2', 'Mysheet']
    
    # добавим данные в лист с именем `Mysheet2`
    >>> ws = wb["Mysheet2"]
    # создадим произвольные данные, используя
    # вложенный генератор списков
    >>> data = [[row*col for col in range(1, 10)] for row in range(1, 31)]
    >>> data
    # [
    #     [1, 2, 3, 4, 5, 6, 7, 8, 9], 
    #     [2, 4, 6, 8, 10, 12, 14, 16, 18], 
    # ...
    # ...
    #     [30, 60, 90, 120, 150, 180, 210, 240, 270]
    # ]
    
    # добавляем данные в выбранный лист
    >>> for row in data:
    ...     ws.append(row)
    ...
    

    Вот и все, данные добавлены… Просто? Не просто, а супер просто!

    Сохранение созданной книги в файл Excel.

    Самый простой и безопасный способ сохранить книгу, это использовать метод Workbook.save() объекта Workbook:

    >>> wb = Workbook()
    >>> wb.save('test.xlsx')
    

    Внимание. Эта операция перезапишет существующий файл без предупреждения!!!

    После сохранения, можно открыть полученный файл в Excel и посмотреть данные, выбрав лист с именем NewPage.

    Примечание. Расширение имени файла не обязательно должно быть xlsx или xlsm, хотя могут возникнуть проблемы с его открытием непосредственно в другом приложении. Поскольку файлы OOXML в основном представляют собой ZIP-файлы, их также можете открыть с помощью своего любимого менеджера ZIP-архивов.

    Сохранение данных книги в виде потока.

    Если необходимо сохранить файл в поток, например, при использовании веб-приложения, такого как Flask или Django, то можно просто предоставить tempfile.NamedTemporaryFile():

    from tempfile import NamedTemporaryFile
    from openpyxl import Workbook
    
    wb = Workbook()
    
    with NamedTemporaryFile() as tmp:
        wb.save(tmp.name)
        tmp.seek(0)
        stream = tmp.read()
    

    Можно указать атрибут template=True, чтобы сохранить книгу как шаблон:

    >>> from openpyxl import load_workbook
    >>> wb = load_workbook('test.xlsx')
    >>> wb.template = True
    >>> wb.save('test_template.xltx')
    

    Примечание. Атрибут wb.template по умолчанию имеет значение False, это означает — сохранить как документ.

    Внимание. Следующее не удастся:

    >>> from openpyxl import load_workbook
    >>> wb = load_workbook('test.xlsx')
    # Необходимо сохранить с расширением *.xlsx
    >>> wb.save('new_test.xlsm') # MS Excel не может открыть документ
    
    # Нужно указать атрибут `keep_vba=True`
    >>> wb = load_workbook('test.xlsm')
    >>> wb.save('new_test.xlsm')
    
    >>> wb = load_workbook('test.xltm', keep_vba=True)
    # Если нужен шаблон документа, то необходимо указать расширение *.xltm.
    >>> wb.save('new_test.xlsm') # MS Excel не может открыть документ
    

    Загрузка документа XLSX из файла.

    Чтобы открыть существующую книгу Excel необходимо использовать функцию openpyxl.load_workbook():

    >>> from openpyxl import load_workbook
    >>> wb2 = load_workbook('test.xlsx')
    >>> print(wb2.sheetnames)
    # ['Mysheet1', 'NewPage', 'Mysheet2', 'Mysheet']
    

    Есть несколько флагов, которые можно использовать в функции openpyxl.load_workbook().

    • data_only: определяет, будут ли содержать ячейки с формулами — формулу (по умолчанию) или только значение, сохраненное/посчитанное при последнем чтении листа Excel.
    • keep_vba определяет, сохраняются ли какие-либо элементы Visual Basic (по умолчанию). Если они сохранены, то они не могут изменяться/редактироваться.

    In this article, we will show you how to get all the sheet names found in an excel file using python openpyxl library.

    Assume we have taken an excel file with the name sampleTutorialsPoint.xlsx containing multiple sheets with some random data. We will return all the sheet names found in a given excel file using the sheetnames attribute.

    sampleTutorialsPoint.xlsx

    firstSheet

    Player Name Age Type Country Team Runs Wickets
    Virat Kohli 33 Batsman India Royal Challengers Bangalore 6300 20
    Bhuvaneshwar Kumar 34 Batsman India Sun Risers Hyderabad 333 140
    Mahendra Singh Dhoni 39 Batsman India Chennai Super Kings 4500 0
    Rashid Khan 28 Bowler Afghanistan Gujarat Titans 500 130

    SheetTwo

    David Warner 34 Batsman Australia Delhi Capitals 5500 12
    Kieron Pollard 35 All rounder West Indies Mumbai Indians 3000 67
    Rohit Sharma 33 Batsman India Mumbai Indians 5456 20
    Kane Williamson 33 Batsman New Zealand Sun Risers Hyderabad 3222 5
    Kagiso Rabada 29 Bowler South Africa Lucknow Capitals 335 111

    3rdsheet

    Tutorials Point Tutorials Point

    Algorithm (Steps)

    Following are the Algorithm/steps to be followed to perform the desired task −

    • Use the import keyword, to import the openpyxl module (Openpyxl is a Python package for interacting with and managing Excel files. Excel 2010 and later files with the xlsx/xlsm/xltx/xltm extensions are supported. Data scientists use Openpyxl for data analysis, data copying, data mining, drawing charts, styling sheets, formula addition, and other operations)

    pip install openpyxl
    
    • Create a variable to store the path of the input excel file.

    • To create/load a workbook object, pass the input excel file to the openpyxl module’s load_workbook() function (loads a workbook).

    • By applying the sheetnames attribute to the workbook, you obtain a list of all the sheetnames.

    • Traverse in the sheetNames List using the for loop and print the corresponding sheetNames.

    Example

    The following program prints all the sheet names found in an input excel file −

    import openpyxl inputExcelFile ="sampleTutorialsPoint.xlsx" newWorkbook = openpyxl.load_workbook(inputExcelFile) print('The Sheet names of the given excel file: ') sheetNames=newWorkbook.sheetnames for name in sheetNames: print(name)

    Output

    On executing, the above program will generate the following output −

    The Sheet names of the given excel file:
    firstSheet
    SheetTwo
    3rdsheet
    

    In our program, we used a sample excel file with dummy data. The excel file comprises a lot of sheets. By applying the sheetnames attribute to the workbook, we get a list of all the sheet names. Then we go through the list one by one, printing the corresponding sheetnames.

    Conclusion

    We learned how to use the openpyxl module to create a workbook from an excel file. We also learned how to extract the sheetnames of an excel file using the sheetnames attribute and how to display the list’s contents one by one.

    Понравилась статья? Поделить с друзьями:
  • Имя книги формула excel
  • Имя книги переменная vba excel
  • Имя книги в excel в формуле
  • Имя книги excel миф
  • Имя класса окна excel