Вставка и удаление строк и столбцов файлов Excel
Введение
При создании нового листа Excel с нуля или работе с существующим листом нам может потребоваться добавить дополнительные строки или столбцы для размещения большего объема данных. Напротив, также может потребоваться удалить строки или столбцы из указанных позиций в листе. Для выполнения этих требований Aspose.Cells предоставляет очень простой набор классов и методов, рассматриваемых ниже.
Управлять строками и столбцами
Aspose.Cells предоставляет класс Workbook, который представляет файл Microsoft Excel. Класс Workbook содержит коллекцию Worksheets, позволяющую получить доступ к каждому листу Excel в файле. Лист представлен классом Worksheet. Класс Worksheet предоставляет коллекцию Cells, представляющую все ячейки на листе.
Коллекция Cells предоставляет несколько методов для управления строками и столбцами на листе. Некоторые из них рассматриваются ниже.
Вставить строки и столбцы
Как вставить строку
Вставьте строку на листе в любом месте, вызвав метод InsertRow коллекции Cells. Метод InsertRow принимает индекс строки, куда будет вставлена новая строка.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Creating a file stream containing the Excel file to be opened | |
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open); | |
// Instantiating a Workbook object | |
// Opening the Excel file through the file stream | |
Workbook workbook = new Workbook(fstream); | |
// Accessing the first worksheet in the Excel file | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Inserting a row into the worksheet at 3rd position | |
worksheet.Cells.InsertRow(2); | |
// Saving the modified Excel file | |
workbook.Save(dataDir + "output.out.xls"); | |
// Closing the file stream to free all resources | |
fstream.Close(); |
Как вставить несколько строк
Для вставки нескольких строк на лист, вызовите метод InsertRows коллекции Cells. Метод InsertRows принимает два параметра:
- Индекс строки, индекс строки, с которой будут вставлены новые строки.
- Количество строк, общее количество строк, которые необходимо вставить.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Creating a file stream containing the Excel file to be opened | |
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open); | |
// Instantiating a Workbook object | |
// Opening the Excel file through the file stream | |
Workbook workbook = new Workbook(fstream); | |
// Accessing the first worksheet in the Excel file | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Inserting 10 rows into the worksheet starting from 3rd row | |
worksheet.Cells.InsertRows(2, 10); | |
// Saving the modified Excel file | |
workbook.Save(dataDir + "output.out.xls"); | |
// Closing the file stream to free all resources | |
fstream.Close(); |
Как вставить строку с форматированием
Чтобы вставить строку с параметрами форматирования, используйте перегрузку InsertRows, которая принимает InsertOptions в качестве параметра. Установите свойство CopyFormatType класса InsertOptions с перечислением CopyFormatType. Перечисление CopyFormatType имеет три элемента, перечисленные ниже.
- SameAsAbove: Форматирует строку так же, как и строка выше.
- SameAsBelow: Форматирует строку так же, как и строка ниже.
- Очистить: Очищает форматирование.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Creating a file stream containing the Excel file to be opened | |
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open); | |
// Instantiating a Workbook object | |
// Opening the Excel file through the file stream | |
Workbook workbook = new Workbook(fstream); | |
// Accessing the first worksheet in the Excel file | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Setting Formatting options | |
InsertOptions insertOptions = new InsertOptions(); | |
insertOptions.CopyFormatType = CopyFormatType.SameAsAbove; | |
// Inserting a row into the worksheet at 3rd position | |
worksheet.Cells.InsertRows(2, 1, insertOptions); | |
// Saving the modified Excel file | |
workbook.Save(dataDir + "InsertingARowWithFormatting.out.xls"); | |
// Closing the file stream to free all resources | |
fstream.Close(); |
Как вставить столбец
Разработчики также могут вставлять столбец в лист на любой позиции, вызвав метод InsertColumn коллекции Cells. Метод InsertColumn принимает индекс столбца, куда будет вставлен новый столбец.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Creating a file stream containing the Excel file to be opened | |
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open); | |
// Instantiating a Workbook object | |
// Opening the Excel file through the file stream | |
Workbook workbook = new Workbook(fstream); | |
// Accessing the first worksheet in the Excel file | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Inserting a column into the worksheet at 2nd position | |
worksheet.Cells.InsertColumn(1); | |
// Saving the modified Excel file | |
workbook.Save(dataDir + "output.out.xls"); | |
// Closing the file stream to free all resources | |
fstream.Close(); |
Удалить строки и столбцы
Как удалить несколько строк
Чтобы удалить несколько строк из листа, вызовите метод DeleteRows коллекции Cells. Метод DeleteRows принимает два параметра:
- Индекс строки, индекс строки, с которой строки будут удалены.
- Количество строк, общее количество строк, которые нужно удалить.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Creating a file stream containing the Excel file to be opened | |
FileStream fstream = new FileStream(dataDir + "Book1.xlsx", FileMode.OpenOrCreate); | |
// Instantiating a Workbook object | |
// Opening the Excel file through the file stream | |
Workbook workbook = new Workbook(fstream); | |
// Accessing the first worksheet in the Excel file | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Deleting 10 rows from the worksheet starting from 3rd row | |
worksheet.Cells.DeleteRows(2, 10); | |
// Saving the modified Excel file | |
workbook.Save(dataDir + "output.xlsx"); | |
// Closing the file stream to free all resources | |
fstream.Close(); |
Как удалить столбец
Чтобы удалить столбец из листа в любом месте, вызовите метод DeleteColumn коллекции Cells. Метод DeleteColumn принимает индекс удаляемого столбца.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Creating a file stream containing the Excel file to be opened | |
FileStream fstream = new FileStream(dataDir + "Book1.xlsx", FileMode.Open); | |
// Instantiating a Workbook object | |
// Opening the Excel file through the file stream | |
Workbook workbook = new Workbook(fstream); | |
// Accessing the first worksheet in the Excel file | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Deleting a column from the worksheet at 5th position | |
worksheet.Cells.DeleteColumn(4); | |
// Saving the modified Excel file | |
workbook.Save(dataDir + "output.xlsx"); | |
// Closing the file stream to free all resources | |
fstream.Close(); |