Вставка и удаление строк и столбцов файлов Excel
Введение
При создании нового листа Excel с нуля или работе с существующим листом нам может потребоваться добавить дополнительные строки или столбцы для размещения большего объема данных. Напротив, также может потребоваться удалить строки или столбцы из указанных позиций в листе. Для удовлетворения этих требований Aspose.Cells для Python via .NET предоставляет очень простой набор классов и методов, описанных ниже.
Управлять строками и столбцами
Aspose.Cells для Python via .NET предоставляет класс Workbook, который представляет файл Microsoft Excel. Класс Workbook содержит коллекцию worksheets, позволяющую получить доступ к каждому листу в файле Excel. Лист представлен классом Worksheet. Класс Worksheet предоставляет коллекцию cells, представляющую все ячейки на листе.
Коллекция cells предоставляет несколько методов для управления строками и столбцами на листе. Некоторые из них рассматриваются ниже.
Вставить строки и столбцы
Как вставить строку
Вставьте строку на листе в любом месте, вызвав метод insert_row коллекции cells. Метод insert_row принимает индекс строки, куда будет вставлена новая строка.
from aspose.cells import Workbook | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Creating a file stream containing the Excel file to be opened | |
fstream = open(dataDir + "book1.xls", "rb") | |
# Instantiating a Workbook object | |
# Opening the Excel file through the file stream | |
workbook = Workbook(fstream) | |
# Accessing the first worksheet in the Excel file | |
worksheet = workbook.worksheets[0] | |
# Inserting a row into the worksheet at 3rd position | |
worksheet.cells.insert_row(2) | |
# Saving the modified Excel file | |
workbook.save(dataDir + "output.out.xls") | |
# Closing the file stream to free all resources | |
fstream.close() |
Как вставить несколько строк
Для вставки нескольких строк на лист, вызовите метод insert_rows коллекции cells. Метод insert_rows принимает два параметра:
- Индекс строки, индекс строки, с которой будут вставлены новые строки.
- Количество строк, общее количество строк, которые необходимо вставить.
from aspose.cells import Workbook | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Creating a file stream containing the Excel file to be opened | |
fstream = open(dataDir + "book1.xls", "rb") | |
# Instantiating a Workbook object | |
# Opening the Excel file through the file stream | |
workbook = Workbook(fstream) | |
# Accessing the first worksheet in the Excel file | |
worksheet = workbook.worksheets[0] | |
# Inserting 10 rows into the worksheet starting from 3rd row | |
worksheet.cells.insert_rows(2, 10) | |
# Saving the modified Excel file | |
workbook.save(dataDir + "output.out.xls") | |
# Closing the file stream to free all resources | |
fstream.close() |
Как вставить строку с форматированием
Чтобы вставить строку с параметрами форматирования, используйте перегрузку insert_rows, которая принимает InsertOptions в качестве параметра. Установите свойство copy_format_type класса InsertOptions с перечислением CopyFormatType. Перечисление CopyFormatType имеет три элемента, перечисленные ниже.
- SAME_AS_ABOVE: Форматирует строку так же, как и выше.
- SAME_AS_BELOW: Форматирует строку так же, как и ниже.
- CLEAR: Очищает форматирование.
from aspose.cells import CopyFormatType, InsertOptions, Workbook | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Creating a file stream containing the Excel file to be opened | |
fstream = open(dataDir + "book1.xls", "rb") | |
# Instantiating a Workbook object | |
# Opening the Excel file through the file stream | |
workbook = Workbook(fstream) | |
# Accessing the first worksheet in the Excel file | |
worksheet = workbook.worksheets[0] | |
# Setting Formatting options | |
insertOptions = InsertOptions() | |
insertOptions.copy_format_type = CopyFormatType.SAME_AS_ABOVE | |
# Inserting a row into the worksheet at 3rd position | |
worksheet.cells.insert_rows(2, 1, insertOptions) | |
# Saving the modified Excel file | |
workbook.save(dataDir + "InsertingARowWithFormatting.out.xls") | |
# Closing the file stream to free all resources | |
fstream.close() |
Как вставить столбец
Разработчики также могут вставлять столбец в лист на любой позиции, вызвав метод insert_column коллекции cells. Метод insert_column принимает индекс столбца, куда будет вставлен новый столбец.
from aspose.cells import Workbook | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Creating a file stream containing the Excel file to be opened | |
fstream = open(dataDir + "book1.xls", "rb") | |
# Instantiating a Workbook object | |
# Opening the Excel file through the file stream | |
workbook = Workbook(fstream) | |
# Accessing the first worksheet in the Excel file | |
worksheet = workbook.worksheets[0] | |
# Inserting a column into the worksheet at 2nd position | |
worksheet.cells.insert_column(1) | |
# Saving the modified Excel file | |
workbook.save(dataDir + "output.out.xls") | |
# Closing the file stream to free all resources | |
fstream.close() |
Удалить строки и столбцы
Как удалить несколько строк
Чтобы удалить несколько строк из листа, вызовите метод delete_rows коллекции cells. Метод delete_rows принимает два параметра:
- Индекс строки, индекс строки, с которой строки будут удалены.
- Количество строк, общее количество строк, которые нужно удалить.
from aspose.cells import Workbook | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Creating a file stream containing the Excel file to be opened | |
fstream = open(dataDir + "Book1.xlsx", "wb") | |
# Instantiating a Workbook object | |
# Opening the Excel file through the file stream | |
workbook = Workbook(fstream) | |
# Accessing the first worksheet in the Excel file | |
worksheet = workbook.worksheets[0] | |
# Deleting 10 rows from the worksheet starting from 3rd row | |
worksheet.cells.delete_rows(2, 10) | |
# Saving the modified Excel file | |
workbook.save(dataDir + "output.xlsx") | |
# Closing the file stream to free all resources | |
fstream.close() |
Как удалить столбец
Чтобы удалить столбец из листа в любом месте, вызовите метод delete_column коллекции Cells. Метод delete_column принимает индекс удаляемого столбца.
from aspose.cells import Workbook | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Creating a file stream containing the Excel file to be opened | |
fstream = open(dataDir + "Book1.xlsx", "rb") | |
# Instantiating a Workbook object | |
# Opening the Excel file through the file stream | |
workbook = Workbook(fstream) | |
# Accessing the first worksheet in the Excel file | |
worksheet = workbook.worksheets[0] | |
# Deleting a column from the worksheet at 5th position | |
worksheet.cells.delete_column(4) | |
# Saving the modified Excel file | |
workbook.save(dataDir + "output.xlsx") | |
# Closing the file stream to free all resources | |
fstream.close() |