Python удаление строки excel

Python для удаления строки в таблице Excel

У меня есть действительно большой файл excel, и мне нужно удалить около 20 000 строк, зависящих от простого условия, и excel не позволит мне удалить такой сложный диапазон при использовании фильтра. Условие:

Если первый столбец содержит значение X, тогда мне нужно удалить всю строку.

Я пытаюсь автоматизировать это с помощью python и xlwt, но я не совсем уверен, с чего начать. Ищу некоторые фрагменты кода, чтобы я начал…
Благодарен за любую помощь, что там!

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

  • прочитать исходный файл
  • открыть новый файл
  • итерация по строкам исходного файла (если первый столбец строки не содержит значения X, добавьте эту строку в новый файл)
  • закрыть оба файла
  • переименуйте новый файл в исходный файл

Вы можете попробовать использовать csv reader:

Мне нравится использовать COM-объекты для такого удовольствия:

import win32com.client from win32com.client import constants f = r"h:\Python\Examples\test.xls" DELETE_THIS = "X" exc = win32com.client.gencache.EnsureDispatch("Excel.Application") exc.Visible = 1 exc.Workbooks.Open(Filename=f) row = 1 while True: exc.Range("B%d" % row).Select() data = exc.ActiveCell.FormulaR1C1 exc.Range("A%d" % row).Select() condition = exc.ActiveCell.FormulaR1C1 if data == '': break elif condition == DELETE_THIS: exc.Rows("%d:%d" % (row, row)).Select() exc.Selection.Delete(Shift=constants.xlUp) else: row += 1 # Before # # a # b # X c # d # e # X d # g # # After # # a # b # d # e # g 

Обычно я записываю фрагменты макросов Excel и склеиваю их вместе с Python, поскольку мне не нравится Visual Basic:-D.

Если вам просто нужно удалить данные (а не “избавиться от” строки, т.е. сдвинуть строки), вы можете попробовать использовать мой модуль PyWorkbooks. Вы можете получить самую последнюю версию здесь:

Существует учебник pdf, в котором вы можете узнать, как его использовать. Счастливое кодирование!

sh.Range(sh.Cells(1,1),sh.Cells(20000,1)).EntireRow.Delete() 

удалит строки с 1 по 20 000 в открытой электронной таблице Excel, поэтому

if sh.Cells(1,1).Value == 'X': sh.Cells(1,1).EntireRow.Delete() 

Я добился использования пакета Pandas. import Pandas как pd

#Read from Excel xl= pd.ExcelFile("test.xls") #Parsing Excel Sheet to DataFrame dfs = xl.parse(xl.sheet_names[0]) #Update DataFrame as per requirement #(Here Removing the row from DataFrame having blank value in "Name" column) dfs = dfs[dfs['Name'] != ''] #Updating the excel sheet with the updated DataFrame dfs.to_excel("test.xls",sheet_name='Sheet1',index=False) 

Источник

Inserting and deleting rows and columns, moving ranges of cells¶

You can insert rows or columns using the relevant worksheet methods:

The default is one row or column. For example to insert a row at 7 (before the existing row 7):

Deleting rows and columns¶

Openpyxl does not manage dependencies, such as formulae, tables, charts, etc., when rows or columns are inserted or deleted. This is considered to be out of scope for a library that focuses on managing the file format. As a result, client code must implement the functionality required in any particular use case.

Читайте также:  Java time types sql

Moving ranges of cells¶

You can also move ranges of cells within a worksheet:

>>> ws.move_range("D4:F10", rows=-1, cols=2) 

This will move the cells in the range D4:F10 up one row, and right two columns. The cells will overwrite any existing cells.

If cells contain formulae you can let openpyxl translate these for you, but as this is not always what you want it is disabled by default. Also only the formulae in the cells themselves will be translated. References to the cells from other cells or defined names will not be updated; you can use the Parsing Formulas translator to do this:

>>> ws.move_range("G4:H10", rows=1, cols=1, translate=True) 

This will move the relative references in formulae in the range by one row and one column.

Merge / Unmerge cells¶

When you merge cells all cells but the top-left one are removed from the worksheet. To carry the border-information of the merged cell, the boundary cells of the merged cell are created as MergeCells which always have the value None. See Styling Merged Cells for information on formatting merged cells.

>>> from openpyxl.workbook import Workbook >>> >>> wb = Workbook() >>> ws = wb.active >>> >>> ws.merge_cells('A2:D2') >>> ws.unmerge_cells('A2:D2') >>> >>> # or equivalently >>> ws.merge_cells(start_row=2, start_column=1, end_row=4, end_column=4) >>> ws.unmerge_cells(start_row=2, start_column=1, end_row=4, end_column=4) 

© Copyright 2010 — 2023, See AUTHORS Revision 4212e3e95a42 .

Versions latest stable 3.1.2 3.1.1 3.1.0 3.1 3.0 2.6 2.5.14 2.5 2.4 Downloads html On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Источник

Use Python to Delete Excel Rows & Columns

This tutorial will show you how to use the Python openpyxl library to delete rows or columns from existing Excel files.

Library

To install the openpyxl library, type the following in a command prompt window:

Sample Dataset

Copy and run the following code to create a sample Excel file to follow the tutorial.

openpyxl created Excel file

Python Delete Excel Rows and Columns

Delete at Known Position

Since we need to delete from existing Excel files, let’s first read the file content into Python. Then we can use the delete_rows() or delete_cols() to remove rows and columns.

Delete 1 Row or Column

If we want to delete just 1 row, just call delete_rows(n), which will delete the nth row from the top. We can ignore the second argument, which equals 1 by default. Similarly, to delete just 1 column, use delete_cols(n) and skip the second argument.

Delete Multiple Rows or Columns

To delete multiple rows or columns, we’ll need to use both arguments. The following code will delete the 2nd row to the 5th row. It means to delete row 2, plus the 3 rows underneath it, for a total of 4 rows.

Читайте также:  Css animation button style

Similarly, to delete multiple columns we need to use both arguments. The below deletes from column 2 (B), and for a total of 2 columns (B and C).

Unfortunately, there’s no easy way to delete multiple non-consecutive rows or columns. We have to delete one by one and figure out the new position of the rows/cols after each delete.

Delete Based on Cell Values

Our dataset contains 2 empty rows at id 4 and 9. Let’s say if the empty rows can appear randomly anywhere in a file, then we don’t know the exact location of those rows (or columns) so we can’t use the delete methods directly.

openpyxl delete empty rows

We need to first find where those rows are. Basically, we need to know which rows have empty values.

In the below code, using ws.iter_rows() we can get tuples of Cell objects. Then from those Cell objects, we can access the cell values and row/column positions.

any() returns True if at least one of the elements is not None, and returns False if all elements are None. We can use this function to locate the empty rows.

Of course, don’t forget to save the changes back to the Excel file!

Источник

Как вставлять и удалять строки и столбцы в Excel на Python

Вставить удалить строки или столбцы в Excel на Python

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

Библиотека Python для вставки или удаления строк и столбцов Excel#

Чтобы вставлять или удалять строки и столбцы в листах XLSX/XLS, мы будем использовать API Aspose.Cells для Python через Java. Это мощный API для работы с электронными таблицами, который предоставляет широкий спектр функций для автоматизации Excel. Вы можете установить API, используя следующую команду pip.

Как вставить строки в Excel с помощью Python#

Ниже приведены шаги для вставки строк на лист Excel в Python.

  • Сначала загрузите файл Excel с помощью класса Workbook.
  • Получите доступ к нужному рабочему листу по индексу, используя метод Workbook.getWorksheets().get(index).
  • Вставьте строки, используя метод Worksheet.getCells().insertRows(rowIndex, totalRows), в котором первый параметр — это индекс строки, а второй параметр — количество строк, которые вы хотите вставить.
  • Наконец, сохраните обновленный файл с помощью метода Workbook.save(string).

В следующем примере кода показано, как вставлять строки на лист Excel с помощью Python.

# Instantiate a Workbook object by excel file path workbook = self.Workbook("Book1.xls") # Access the first worksheet in the Excel file worksheet = workbook.getWorksheets().get(0) # Insert a row into the worksheet at 3rd position worksheet.getCells().insertRows(2,1) # Save the modified Excel file in default (that is Excel 2003) format workbook.save("Insert Row.xls") 

Как вставить столбцы в Excel на Python#

Ниже приведены шаги для вставки столбцов в рабочий лист Excel с помощью Python.

  • Сначала загрузите файл Excel с помощью класса Workbook.
  • Получите доступ к нужному рабочему листу по индексу, используя метод Workbook.getWorksheets().get(index).
  • Вставьте столбцы с помощью метода Worksheet.getCells().insertColumns(columnIndex, totalColumns), в котором первым параметром является индекс столбца, а вторым параметром — количество столбцов, которые вы хотите вставить.
  • Наконец, сохраните обновленный файл с помощью метода Workbook.save(string).
Читайте также:  Php что такое exit

В следующем примере кода показано, как вставить столбцы на лист Excel с помощью Python.

# Instantiate a Workbook object by excel file path workbook = self.Workbook('Book1.xls') # Access the first worksheet in the Excel file worksheet = workbook.getWorksheets().get(0) # Insert a column into the worksheet at 2nd position worksheet.getCells().insertColumns(1,1) # Save the modified Excel file in default (that is Excel 2003) format workbook.save("Insert Column.xls") 

Удалить строки в Excel XLSX в Python#

Ниже приведены шаги по удалению строк из рабочего листа Excel с помощью Python.

  • Сначала загрузите файл Excel с помощью класса Workbook.
  • Получите доступ к нужному рабочему листу по индексу, используя метод Workbook.getWorksheets().get(index).
  • Удаляйте строки с помощью метода Worksheet.getCells().deleteRows(rowIndex, totalRows), в котором первый параметр — это индекс строки, а второй параметр — количество строк, которые вы хотите удалить.
  • Наконец, сохраните обновленный файл с помощью метода Workbook.save(string).

В следующем примере кода показано, как удалить строки из листа Excel в Python.

# Instantiate a Workbook object by excel file path workbook = self.Workbook("Book1.xls") # Access the first worksheet in the Excel file worksheet = workbook.getWorksheets().get(0) # Delete 10 rows from the worksheet starting from 3rd row worksheet.getCells().deleteRows(2,10,True) # Save the modified Excel file in default (that is Excel 2003) format workbook.save("Insert Row.xls") 

Удалить столбцы в Excel XLSX в Python#

Ниже приведены шаги по удалению столбцов из рабочего листа Excel с помощью Python.

  • Сначала загрузите файл Excel с помощью класса Workbook.
  • Получите доступ к нужному рабочему листу по индексу, используя метод Workbook.getWorksheets().get(index).
  • Удалите столбцы с помощью метода Worksheet.getCells().insertColumns(columnIndex, totalColumns, updateReference). Первый параметр — это индекс столбца, второй параметр — это количество столбцов, которые вы хотите удалить, а третий параметр указывает, нужно ли обновлять ссылки на других листах.
  • Наконец, сохраните обновленный файл с помощью метода Workbook.save(string).

В следующем примере кода показано, как удалить столбцы из листа Excel с помощью Python.

# Instantiate a Workbook object by excel file path workbook = self.Workbook('Book1.xls') # Access the first worksheet in the Excel file worksheet = workbook.getWorksheets().get(0) # Delete a column from the worksheet at 2nd position worksheet.getCells().deleteColumns(1,1,True) # Save the modified Excel file in default (that is Excel 2003) format workbook.save("Insert Column.xls") 

Получите бесплатную лицензию API#

Вы можете получить бесплатную временную лицензию, чтобы использовать API без ограничений пробной версии.

Вывод#

В этой статье вы узнали, как работать со строками и столбцами в Excel. В частности, вы видели, как вставлять или удалять строки и столбцы в листах Excel с помощью Python. Кроме того, вы можете узнать больше об API Python Excel, используя документацию. Кроме того, вы можете поделиться с нами своими вопросами через наш форум.

Смотрите также#

Источник

Оцените статью