Insertar y eliminar filas y columnas de un archivo de Excel

Introducción

Ya sea creando una nueva hoja de trabajo desde cero o trabajando en una hoja de trabajo existente, es posible que necesitemos agregar filas o columnas adicionales para acomodar más datos. A la inversa, es posible que también necesitemos eliminar filas o columnas de posiciones específicas en la hoja de trabajo. Para cumplir con estos requisitos, Aspose.Cells proporciona un conjunto de clases y métodos muy simple, que se analiza a continuación.

Administrar filas y columnas

Aspose.Cells proporciona una claseLibro de trabajo , que representa un archivo de Excel Microsoft. ÉlLibro de trabajo la clase contiene unHojas de trabajo colección que permite el acceso a cada hoja de trabajo en un archivo de Excel. Una hoja de trabajo está representada por elHoja de cálculo clase. ÉlHoja de cálculo la clase proporciona unCellscolección que representa todas las celdas de la hoja de trabajo.

ÉlCellsLa colección proporciona varios métodos para administrar filas y columnas en una hoja de cálculo. Algunos de éstos se discuten a continuación.

Insertar filas y columnas

Insertar una fila

Inserte una fila en la hoja de trabajo en cualquier lugar llamando alInsertar fila metodo de laCells recopilación. ÉlInsertar filaEl método toma el índice de la fila donde se insertará la nueva fila.

// 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();

Insertar varias filas

Para insertar varias filas en una hoja de trabajo, llame alInsertar filas metodo de laCells recopilación. ÉlInsertar filasEl método toma dos parámetros:

  • Índice de fila, el índice de la fila desde donde se insertarán las nuevas filas.
  • Número de filas, el número total de filas que deben insertarse.
// 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();

Insertar una fila con formato

Para insertar una fila con opciones de formato, use elInsertar filassobrecarga que tomaOpciones de inserción como parámetro. Selecciona elTipo de formato de copia propiedad deOpciones de inserción clase conTipo de formato de copia Enumeración. ÉlTipo de formato de copiaLa enumeración tiene tres miembros, como se indica a continuación.

  • SameAsAbove: da formato a la fila igual que la fila anterior.
  • SameAsBelow: da formato a la fila igual que la fila de abajo.
  • Borrar: Borra el formato.
// 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();

Insertar una columna

Los desarrolladores también pueden insertar una columna en la hoja de trabajo en cualquier ubicación llamando alInsertarColumna metodo de laCellsrecopilación. ÉlInsertarColumnaEl método toma el índice de la columna donde se insertará la nueva columna.

// 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();

Eliminar filas y columnas

Eliminar varias filas

Para eliminar varias filas de una hoja de trabajo, llame alEliminar filas metodo de laCells recopilación. ÉlEliminar filasEl método toma dos parámetros:

  • Índice de fila, el índice de la fila desde donde se eliminarán las filas.
  • Número de filas, el número total de filas que deben eliminarse.
// 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();

Eliminar una columna

Para eliminar una columna de la hoja de cálculo en cualquier lugar, llame alEliminarColumna metodo de laCells recopilación. ÉlEliminarColumnaEl método toma el índice de la columna a eliminar.

// 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();