Cómo editar un archivo de Excel en C#

C# Edit Excel File

This article was translated from English: Does it need improvement?
Translated
View the article in English

Developers have to be careful when they set out to modify and edit Excel files in C# because it can be easy for one misstep to change the whole document. Being able to rely on simple and efficient lines of code helps reduce the risk of error, and makes it easier for us to edit or delete Excel files programmatically. Today we'll walk through the steps necessary to edit Excel files in C# correctly and quickly using tested functions.

Quickstart: Edit a Specific Cell Value with IronXL

This example shows how easy it is to load an existing Excel file, update a single cell, and save the changes using IronXL. Get started in under 5 lines, no Interop required.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronXL with NuGet Package Manager

    PM > Install-Package IronXL.Excel

  2. Copy and run this code snippet.

    IronXL.WorkBook.Load("file.xlsx").GetWorkSheet("Sheet1")["C3"].Value = "Hello IronXL";
    // then save your workbook
    iroExcelWorkBook.SaveAs("file.xlsx");
  3. Deploy to test on your live environment

    Start using IronXL in your project today with a free trial
    arrow pointer

Step 1

1. C# Edit Excel Files using the IronXL Library

For this tutorial, we'll be using the functions defined by IronXL, a C# Excel library. To use these functions you'll need to first download and install it into your project (free for development).

You can either Download IronXL.zip or read more and install via the NuGet package page.

Once you've installed it, let's get started!


Install-Package IronXL.Excel

Replace x.x.x with the appropriate version number as needed.


How to Tutorial

2. Edit Specific Cell Values

First, we will look at how to edit specific cell values of an Excel SpreadSheet.

For this purpose, we import the Excel SpreadSheet which is to be modified, and then access its WorkSheet. Then we can apply the modifications as shown below.

:path=/static-assets/excel/content-code-examples/how-to/csharp-edit-excel-file-specific-cell-value.cs
using IronXL;

// Load the Excel workbook
WorkBook wb = WorkBook.Load("sample.xlsx");
// Access a specific worksheet
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Access specific cell by identifying its row and column, then modify its value
ws.Rows[3].Columns[1].Value = "New Value";
// Save changes to the workbook
wb.SaveAs("sample.xlsx");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Here are before and after screenshots of Excel SpreadSheet sample.xlsx:

Before After
before after

We can see how simple it is to modify the Excel SpreadSheet value.

If needed, there is also an alternative way to edit the specific cell value by cell address:

// Alternative way to access specific cell and apply changes
ws["B4"].Value = "New Value";
// Alternative way to access specific cell and apply changes
ws["B4"].Value = "New Value";
' Alternative way to access specific cell and apply changes
ws("B4").Value = "New Value"
$vbLabelText   $csharpLabel

3. Edit Full Row Values

It is pretty simple to edit full row values of an Excel SpreadSheet with a static value.

:path=/static-assets/excel/content-code-examples/how-to/csharp-edit-excel-file-row-value.cs
using IronXL;

WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Setting a static value for the entire row
ws.Rows[3].Value = "New Value";
wb.SaveAs("sample.xlsx");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

See the screenshots of sample.xlsx below:

Before After
before after

For this, we also can edit the value of a specific range of the row, by using range function:

// Editing a specific range of a row
ws["A3:E3"].Value = "New Value";
// Editing a specific range of a row
ws["A3:E3"].Value = "New Value";
' Editing a specific range of a row
ws("A3:E3").Value = "New Value"
$vbLabelText   $csharpLabel

4. Edit Full Column Values

In the same way as above, we can easily edit full columns of Excel SpreadSheet values with a single value.

:path=/static-assets/excel/content-code-examples/how-to/csharp-edit-excel-file-full-column.cs
using IronXL;

WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Setting a static value for the entire column
ws.Columns[1].Value = "New Value";
wb.SaveAs("sample.xlsx");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Which will produce our sample.xlsx spreadsheet as such:

Before After
before after

5. Edit Full Row with Dynamic Values

Using IronXL, it is also possible to edit specific rows with dynamic values. This means we can edit a full row by assigning dynamic values for each cell. Let's see the example:

:path=/static-assets/excel/content-code-examples/how-to/csharp-edit-excel-file-full-row-dynamic.cs
using IronXL;
using System.Linq;

WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
for (int i = 0; i < ws.Columns.Count(); i++)
{
    // Assign dynamic values to each cell in the row
    ws.Rows[3].Columns[i].Value = "New Value " + i.ToString();
}
wb.SaveAs("sample.xlsx");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

In the table below, we see the screenshots of Excel SpreadSheet sample.xlsx from this output:

Before After
before after

6. Edit Full Column with Dynamic Values

It is also simple to edit specific columns with dynamic values.

:path=/static-assets/excel/content-code-examples/how-to/csharp-edit-excel-file-full-column-dynamic.cs
using IronXL;
using System.Linq;

WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
for (int i = 0; i < ws.Rows.Count(); i++)
{
    // Skip the first row if it's used as a header
    if (i == 0)
        continue;
    // Assign dynamic values to each cell in the column
    ws.Rows[i].Columns[1].Value = "New Value " + i.ToString();
}
wb.SaveAs("sample.xlsx");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

With the table results of sample.xlsx below:

Before After
before after

7. Replace Spreadsheet Values

If we want to replace any type of value with an updated value in an Excel SpreadSheet, we can use the function named Replace. Using this function, we can replace the data of Excel SpreadSheet in any required situation.

7.1. Replace Specific Value of Complete WorkSheet

To replace a specific value of a complete Excel WorkSheet with an updated value, we just access the WorkSheet ws (same as in the above examples) and apply the Replace function like this.

// Replace a specific value in the entire worksheet
ws.Replace("old value", "new value");
// Replace a specific value in the entire worksheet
ws.Replace("old value", "new value");
' Replace a specific value in the entire worksheet
ws.Replace("old value", "new value")
$vbLabelText   $csharpLabel

This function will replace old value with new value in a complete Excel WorkSheet.

Don't forget to save the file after any change, as shown in the examples above.

7.2. Replace the Values of Specific Row

If you only want to make changes to a specific row instead of the whole worksheet, use this code.

// Replace a specific value in a specific row
ws.Rows[2].Replace("old value", "new value");
// Replace a specific value in a specific row
ws.Rows[2].Replace("old value", "new value");
' Replace a specific value in a specific row
ws.Rows(2).Replace("old value", "new value")
$vbLabelText   $csharpLabel

The above code will replace old value with new value only in row number 2. The rest of the WorkSheet remains the same.

7.3. Replace the Values of Row Range

We also can replace the values within a specific range as follows:

// Replace specific values in a row range
ws["From Cell Address : To Cell Address"].Replace("old value", "new value");
// Replace specific values in a row range
ws["From Cell Address : To Cell Address"].Replace("old value", "new value");
' Replace specific values in a row range
ws("From Cell Address : To Cell Address").Replace("old value", "new value")
$vbLabelText   $csharpLabel

Suppose, if we want to replace an old value with a new value, just in the range from B4 to E4 of row no 4, then we would write it like this:

ws["B4:E4"].Replace("old value", "new value");
ws["B4:E4"].Replace("old value", "new value");
ws("B4:E4").Replace("old value", "new value")
$vbLabelText   $csharpLabel

7.4. Replace the Values of Specific Column

We can also replace the values of a specific column, and the rest of the worksheet remains the same.

// Replace specific values in a column
ws.Columns[1].Replace("old value", "new value");
// Replace specific values in a column
ws.Columns[1].Replace("old value", "new value");
' Replace specific values in a column
ws.Columns(1).Replace("old value", "new value")
$vbLabelText   $csharpLabel

The above code will replace old value with new value just for column number 1.

7.5. Replace the Values of Column Range

By the following way, we also can use the range function to replace within a range of a specific column.

// Replace specific values in a column range
ws["B5:B10"].Replace("old value", "new value");
// Replace specific values in a column range
ws["B5:B10"].Replace("old value", "new value");
' Replace specific values in a column range
ws("B5:B10").Replace("old value", "new value")
$vbLabelText   $csharpLabel

The above code will replace old value with new value just within range from B5 to B10 for column B.


8. Remove Row from Excel WorkSheet

IronXL provides a very simple function to remove a specific row of an Excel WorkSheet. Let's see the example.

:path=/static-assets/excel/content-code-examples/how-to/csharp-edit-excel-file-row-value.cs
using IronXL;

WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Setting a static value for the entire row
ws.Rows[3].Value = "New Value";
wb.SaveAs("sample.xlsx");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The above code will remove row number 3 of sample.xlsx as shown in the following table:

Before After
before after

9. Remove WorkSheet from Excel File

If we want to remove a complete WorkSheet of an Excel file, we can use the following method:

// Remove a worksheet by its index
wb.RemoveWorkSheet(1); // by sheet indexing
// Remove a worksheet by its index
wb.RemoveWorkSheet(1); // by sheet indexing
' Remove a worksheet by its index
wb.RemoveWorkSheet(1) ' by sheet indexing
$vbLabelText   $csharpLabel

wb is the WorkBook, same as in the above examples. If we want to remove a worksheet by name, then:

// Remove a worksheet by its name
wb.RemoveWorkSheet("Sheet1"); //by sheet name
// Remove a worksheet by its name
wb.RemoveWorkSheet("Sheet1"); //by sheet name
' Remove a worksheet by its name
wb.RemoveWorkSheet("Sheet1") 'by sheet name
$vbLabelText   $csharpLabel

IronXL is rich with many more functions by which we can easily perform any type of editing and deletion in Excel SpreadSheets. Please reach out to our dev team if you have any questions for use in your project.


Library Quick Access

IronXL Library Documentation

Explore the full capabilities of IronXL C# Library with various functions for editing, deleting, styling, and perfecting your Excel workbooks.

IronXL Library Documentation
Documentation related to 9. Remove WorkSheet from Excel File

Preguntas Frecuentes

¿Cómo puedo editar archivos de Excel en C# sin usar Interop?

Puede editar archivos de Excel en C# sin usar Interop al utilizar la biblioteca IronXL. IronXL proporciona una variedad de métodos para modificar documentos Excel, como editar celdas, filas y columnas, e incluso eliminar hojas de trabajo.

¿Cómo modifico los valores de celda en un archivo de Excel usando IronXL?

Para modificar valores de celda en un archivo de Excel usando IronXL, cargue el libro de Excel y acceda a la hoja de trabajo específica. Puede cambiar el valor de la celda especificando los índices de fila y columna y luego guardando el libro.

¿Cuál es el método para reemplazar valores en una aplicación Excel en C#?

En una aplicación Excel en C#, puede reemplazar valores usando la función Replace de IronXL. Esto le permite reemplazar valores específicos en toda la hoja de trabajo, dentro de una fila, columna o rango particular.

¿Cómo puedo eliminar una hoja de trabajo de un archivo Excel programáticamente en C#?

Puede eliminar una hoja de trabajo de un archivo Excel programáticamente en C# usando el método RemoveWorkSheet de IronXL. Puede especificar la hoja de trabajo a eliminar por su nombre o índice.

¿Puedo editar filas completas en un archivo de Excel usando C#?

Sí, con IronXL, puede editar filas completas en un archivo de Excel usando C#. Puede asignar valores estáticos o dinámicos a las celdas dentro de una fila iterando a través de las columnas.

¿Es posible establecer un valor estático para una columna completa en un archivo de Excel?

Sí, IronXL le permite establecer un valor estático para toda una columna en un archivo de Excel. También puede usar valores dinámicos si es necesario, iterando sobre cada celda en la columna.

¿Cómo elimino una fila específica de una hoja de cálculo Excel usando C#?

Para eliminar una fila específica de una hoja de cálculo Excel usando C#, use el método RemoveRow de la biblioteca IronXL, especificando la fila que desea eliminar.

¿Cuáles son los pasos iniciales para comenzar a editar archivos de Excel usando C#?

Para comenzar a editar archivos de Excel usando C#, primero descargue e instale la biblioteca IronXL. Luego, cargue su libro de Excel, seleccione la hoja de trabajo que desea editar y utilice las funciones de IronXL para modificar celdas, filas, columnas o hojas de trabajo según sea necesario.

¿IronXL es adecuado para entornos de desarrollo?

Sí, IronXL es altamente adecuado para entornos de desarrollo. Se puede usar libremente con fines de desarrollo y ofrece una suite completa de funciones para editar archivos de Excel programáticamente.

¿Cómo puedo convertir un archivo de Excel a un formato diferente usando C#?

IronXL permite la conversión de archivos de Excel a diferentes formatos usando sus funciones de exportación. Puede guardar su libro de Excel modificado en formatos como CSV, HTML o PDF usando los métodos de IronXL.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 1,686,155 | Versión: 2025.11 recién lanzado