Cómo escribir en archivos de Excel en .NET con C#

Write Excel .NET Functions

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

Many C# application projects require us to update files and write new data in Excel spreadsheets programmatically. Excel .NET capabilities can sometimes be complicated, but using the IronXL library, this task is quite simple and allows working with Excel spreadsheets in any format. No bulk lines of code, just access to the specific cells and the custom values you assign.

Quickstart: Write a Value to a Specific Cell

This example shows how effortlessly you can write a value into a single cell using IronXL and save the Excel file in just a couple of lines—get started without boilerplate or complexity.

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.

    worksheet["A1"].Value = "Hello, IronXL!";
    workbook.SaveAs("output.xlsx");
  3. Deploy to test on your live environment

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

Write Excel .NET Instructions

  • Download the Library for Excel .NET
  • Write values in specific cells
  • Write static values in multiple cells
  • Write dynamic values in cell range
  • Replace cell values in specific row, column, range, and more
How To Work related to Write Excel .NET Functions

Access Excel Files

Let's start by accessing the Excel file in which we want to write the data. Let's open the Excel file in our project, and then open its specific worksheet using the following code.

:path=/static-assets/excel/content-code-examples/how-to/write-excel-net-load-file.cs
// Load Excel file in the project
WorkBook workBook = WorkBook.Load("path");
' Load Excel file in the project
Dim workBook As WorkBook = WorkBook.Load("path")
$vbLabelText   $csharpLabel

The above will open the specified Excel file. Next, access the worksheet.

:path=/static-assets/excel/content-code-examples/how-to/write-excel-net-get-sheet.cs
// Open Excel WorkSheet
WorkSheet workSheet = workBook.GetWorkSheet("Sheet1");
' Open Excel WorkSheet
Dim workSheet As WorkSheet = workBook.GetWorkSheet("Sheet1")
$vbLabelText   $csharpLabel

The Excel worksheet will open in worksheet and we can use it to write any type of data in the Excel file. Learn more about how to load Excel files and access worksheets in different ways through the examples in the link.

Note: Don't forget to add the reference to IronXL in your project and import the library by using using IronXL.


Write Value in Specific Cell

We can write in an Excel file using many different methods, but the basic approach is using ExcelCell. For this purpose, any cell of the opened Excel worksheet can be accessed and a value written in it as follows:

:path=/static-assets/excel/content-code-examples/how-to/write-excel-net-assign-cell.cs
workSheet["Cell Address"].Value="Assign the Value";
workSheet("Cell Address").Value="Assign the Value"
$vbLabelText   $csharpLabel

Here's an example of how to use the above function to write in an Excel Cell in our C# project.

:path=/static-assets/excel/content-code-examples/how-to/write-excel-net-assign-cell-full.cs
using IronXL;

// Load Excel file
WorkBook workBook = WorkBook.Load("sample.xlsx");

// Open WorkSheet of sample.xlsx
WorkSheet workSheet = workBook.GetWorkSheet("Sheet1");

// Access A1 cell and write the value
workSheet["A1"].Value = "new value";

// Save changes
workBook.SaveAs("sample.xlsx");
Imports IronXL

' Load Excel file
Private workBook As WorkBook = WorkBook.Load("sample.xlsx")

' Open WorkSheet of sample.xlsx
Private workSheet As WorkSheet = workBook.GetWorkSheet("Sheet1")

' Access A1 cell and write the value
Private workSheet("A1").Value = "new value"

' Save changes
workBook.SaveAs("sample.xlsx")
$vbLabelText   $csharpLabel

This code will write new value in cell A1 of the worksheet Sheet1 in the Excel file sample.xlsx. In the same way, we can insert values in any cell address of an Excel file.

Note: Don't forget to save the Excel file after writing new values in the worksheet, as shown in the example above.

Force Assign the Exact Value

When setting the Value property, IronXL will try to convert it to its corresponding value type. Sometimes, this evaluation is undesirable since the user wants to force assign the exact value to the cell without conversion. To do this, assign the value as a string. In IronXL, simply use StringValue instead of Value to achieve the same effect.

:path=/static-assets/excel/content-code-examples/how-to/write-excel-net-assign-stringvalue.cs
// Assign value as string
workSheet["A1"].StringValue = "4402-12";
' Assign value as string
workSheet("A1").StringValue = "4402-12"
$vbLabelText   $csharpLabel

Write Static Values in a Range

We can write new values in multiple cells, called a range, as follows:

// Assign a static value to a range of cells
worksheet["B2:C5"].Value = "static value";
// Assign a static value to a range of cells
worksheet["B2:C5"].Value = "static value";
' Assign a static value to a range of cells
worksheet("B2:C5").Value = "static value"
$vbLabelText   $csharpLabel

In this way, we specify the range of cells From to To where the data will be written. The new value will be written in all the cells which lie in this range. To understand more about C# Excel Range, check out the examples here.

Let's see how to write a range in action using the example below.

:path=/static-assets/excel/content-code-examples/how-to/write-excel-net-assign-cell-range-full.cs
using IronXL;

// Load Excel file
WorkBook workBook = WorkBook.Load("sample.xlsx");

// Open WorkSheet of sample.xlsx
WorkSheet workSheet = workBook.GetWorkSheet("Sheet1");

// Specify range row wise and write new value
workSheet["B2:B9"].Value = "new value";

// Specify range column wise and write new value
workSheet["C3:C7"].Value = "new value";

// Save changes
workBook.SaveAs("sample.xlsx");
Imports IronXL

' Load Excel file
Private workBook As WorkBook = WorkBook.Load("sample.xlsx")

' Open WorkSheet of sample.xlsx
Private workSheet As WorkSheet = workBook.GetWorkSheet("Sheet1")

' Specify range row wise and write new value
Private workSheet("B2:B9").Value = "new value"

' Specify range column wise and write new value
Private workSheet("C3:C7").Value = "new value"

' Save changes
workBook.SaveAs("sample.xlsx")
$vbLabelText   $csharpLabel

This code will write new value from B2 to C5 in the worksheet Sheet1 of the Excel file sample.xlsx. It uses static values for the Excel cells.


Write Dynamic Values in a Range

We can also add dynamic values to a range, as seen below.

:path=/static-assets/excel/content-code-examples/how-to/write-excel-net-assign-dynamic-value.cs
using IronXL;

// Load Excel file
WorkBook workBook = WorkBook.Load("sample.xlsx");

// Open WorkSheet of sample.xlsx
WorkSheet workSheet = workBook.GetWorkSheet("Sheet1");

// Specify range in which we want to write the values
for (int i = 2; i <= 7; i++)
{
    // Write the Dynamic value in one row
    workSheet["B" + i].Value = "Value" + i;

    // Write the Dynamic value in another row
    workSheet["D" + i].Value = "Value" + i;
}

// Save changes
workBook.SaveAs("sample.xlsx");
Imports IronXL

' Load Excel file
Private workBook As WorkBook = WorkBook.Load("sample.xlsx")

' Open WorkSheet of sample.xlsx
Private workSheet As WorkSheet = workBook.GetWorkSheet("Sheet1")

' Specify range in which we want to write the values
For i As Integer = 2 To 7
	' Write the Dynamic value in one row
	workSheet("B" & i).Value = "Value" & i

	' Write the Dynamic value in another row
	workSheet("D" & i).Value = "Value" & i
Next i

' Save changes
workBook.SaveAs("sample.xlsx")
$vbLabelText   $csharpLabel

The above code will write dynamic values in columns B from 2 to 7 in the Excel file sample.xlsx. We can see the result of the code on sample.xlsx.

1excel related to Write Dynamic Values in a Range

Replace Excel Cell Value

Using IronXL, we can easily write a new value to replace the old value, using the Replace() function as follows:

:path=/static-assets/excel/content-code-examples/how-to/write-excel-net-replace.cs
workSheet.Replace("old value", "new value");
workSheet.Replace("old value", "new value")
$vbLabelText   $csharpLabel

The above function will write new value overwriting the old value in the complete Excel worksheet.

Replace Cell Value in Specific Row

If we want to write a new value only in one specific row, do as follows:

:path=/static-assets/excel/content-code-examples/how-to/write-excel-net-replace-row.cs
workSheet.Rows[RowIndex].Replace("old value", "new value");
workSheet.Rows(RowIndex).Replace("old value", "new value")
$vbLabelText   $csharpLabel

This will write new value over the old value in only the specified row index.

Replace Cell Value in Specific Column

Similarly, if we want to write new value over the old value within a specific column, do as follows:

:path=/static-assets/excel/content-code-examples/how-to/write-excel-net-replace-column.cs
workSheet.Columns[ColumnIndex].Replace("old value", "new Value");
workSheet.Columns(ColumnIndex).Replace("old value", "new Value")
$vbLabelText   $csharpLabel

The above code will write new value to replace the old value, but only in the specified column index. The rest of the worksheet remains the same.

Replace Cell Value in Specific Range

IronXL also provides a way to write a new value replacing the old value, only in a specified range.

:path=/static-assets/excel/content-code-examples/how-to/write-excel-net-replace-range.cs
workSheet["From Cell Address : To Cell Address"].Replace("old value", "new value");
workSheet("From Cell Address : To Cell Address").Replace("old value", "new value")
$vbLabelText   $csharpLabel

This will write new value above old value, just in the cells which lie in the specified range.

Let's see the example of how to use all of the above functions to write new values to replace old values in an Excel worksheet.

Example of all Functions

:path=/static-assets/excel/content-code-examples/how-to/write-excel-net-replace-full.cs
using IronXL;

WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.GetWorkSheet("Sheet1");

// Write new above old in complete WorkSheet
workSheet.Replace("old", "new");

// Write new above old just in row no 6 of WorkSheet
workSheet.Rows[5].Replace("old", "new");

// Write new above old just in column no 5 of WorkSheet
workSheet.Columns[4].Replace("old", "new");

// Write new above old just from A5 to H5 of WorkSheet
workSheet["A5:H5"].Replace("old", "new");

workBook.SaveAs("sample.xlsx");
Imports IronXL

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
Private workSheet As WorkSheet = workBook.GetWorkSheet("Sheet1")

' Write new above old in complete WorkSheet
workSheet.Replace("old", "new")

' Write new above old just in row no 6 of WorkSheet
workSheet.Rows(5).Replace("old", "new")

' Write new above old just in column no 5 of WorkSheet
workSheet.Columns(4).Replace("old", "new")

' Write new above old just from A5 to H5 of WorkSheet
workSheet("A5:H5").Replace("old", "new")

workBook.SaveAs("sample.xlsx")
$vbLabelText   $csharpLabel

For more information about how to write Excel .NET applications and more, check out our full tutorial on how to Open and Write Excel Files C#.


Tutorial Quick Access

Read API Reference

Read the IronXL documentation including lists of all functions, features, namespaces, classes, and enums available to you in the library.

Read API Reference
Documentation related to Tutorial Quick Access

Preguntas Frecuentes

¿Cómo comienzo a escribir archivos de Excel en .NET?

Para comenzar con IronXL, descargue la biblioteca e inclúyala en su proyecto. Importe la biblioteca usando using IronXL en su código C#.

¿Cómo puedo escribir un valor en una celda específica en una hoja de cálculo de Excel?

Para escribir un valor en una celda específica usando IronXL, acceda a la celda usando su dirección, como worksheet['A1'], y asigne un valor usando la propiedad .Value.

¿Cómo asigno un valor estático a un rango de celdas en Excel?

Para asignar un valor estático a un rango usando IronXL, especifique el rango usando direcciones de celdas, como worksheet['B2:C5'], y establezca la propiedad .Value al valor estático deseado.

¿Puedo escribir valores dinámicos en un rango de celdas en Excel?

Sí, con IronXL, puede escribir valores dinámicos en un rango usando bucles o lógica personalizada. Por ejemplo, puede iterar sobre direcciones de celdas y asignar valores dinámicos según sus requisitos.

¿Cómo reemplazo valores en celdas de Excel?

Usando IronXL, puede usar el método Replace() en la hoja de cálculo, fila, columna o rango especificado para reemplazar 'valor antiguo' con 'valor nuevo'.

¿Cuál es la diferencia entre usar Value y StringValue?

En IronXL, la propiedad .Value puede convertir el valor asignado a un formato específico de tipo, mientras que .StringValue asigna el valor como una cadena, evitando la conversión.

¿Cómo puedo abrir y acceder a una hoja de cálculo específica en un archivo de Excel?

Use WorkBook.Load('path/to/your/excel-file.xlsx') de IronXL para cargar el archivo y workbook.GetWorkSheet('SheetName') para acceder a una hoja de cálculo específica.

¿Es necesario guardar el archivo de Excel después de escribir nuevos valores?

Sí, al usar IronXL, debe guardar el archivo de Excel después de realizar cambios usando el método workbook.SaveAs('filename.xlsx') para persistir sus cambios.

¿Cómo escribo un nuevo valor para reemplazar un valor antiguo en una fila específica?

Con IronXL, acceda a la fila usando worksheet.Rows[index] y luego llame al método Replace() con los valores antiguos y nuevos.

¿Puedo reemplazar valores en una columna específica?

Sí, usando IronXL, acceda a la columna usando worksheet.Columns['A'] y use el método Replace() para sustituir valores antiguos por nuevos en esa columna.

¿Cómo aseguro que mi proyecto C# pueda interactuar con archivos de Excel?

Asegúrese de que su proyecto C# haga referencia a la biblioteca IronXL descargándola y agregándola a las referencias de su proyecto. Esto facilita la interacción con archivos de Excel.

¿Cuáles son algunos problemas comunes al escribir en archivos de Excel en .NET?

Los problemas comunes incluyen no hacer referencia correctamente a la biblioteca IronXL, formato incorrecto de direcciones de celdas y olvidar guardar los cambios. Asegure la configuración y sintaxis adecuadas.

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