Write Excel .NET Functions
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.
Get started with IronXL
Start using IronXL in your project today with a free trial.
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
// Import necessary namespaces
using IronXL;
using System;
// The following code demonstrates loading an Excel file using the IronXL library.
// IronXL is a library specifically used for handling Excel files in .NET.
// Ensure the IronXL library is referenced in your project.
// You can usually add it via NuGet package manager in your IDE.
// Attempt to load an Excel file.
// A WorkBook object represents the loaded Excel file.
// The Load method is used to load the file and it requires an accurate path to the file.
try
{
// Replace "path_to_your_excel_file.xlsx" with the actual file path to your Excel file.
WorkBook workBook = WorkBook.Load("path_to_your_excel_file.xlsx");
// If the file loads successfully, output a confirmation message to the console.
Console.WriteLine("Excel file successfully loaded.");
}
catch (Exception ex)
{
// This block will catch any exceptions thrown during the loading process.
// It will output an error message to the console providing details of the exception.
Console.WriteLine($"An error occurred while loading the Excel file: {ex.Message}");
}
// Additional Notes:
// - Be sure that the Excel file path is correct, and the application has permissions to access it.
// - The use of a try-catch block helps in gracefully handling any runtime errors
// that may occur while attempting to load the Excel file.
' Import necessary namespaces
Imports IronXL
Imports System
' The following code demonstrates loading an Excel file using the IronXL library.
' IronXL is a library specifically used for handling Excel files in .NET.
' Ensure the IronXL library is referenced in your project.
' You can usually add it via NuGet package manager in your IDE.
' Attempt to load an Excel file.
' A WorkBook object represents the loaded Excel file.
' The Load method is used to load the file and it requires an accurate path to the file.
Try
' Replace "path_to_your_excel_file.xlsx" with the actual file path to your Excel file.
Dim workBook As WorkBook = WorkBook.Load("path_to_your_excel_file.xlsx")
' If the file loads successfully, output a confirmation message to the console.
Console.WriteLine("Excel file successfully loaded.")
Catch ex As Exception
' This block will catch any exceptions thrown during the loading process.
' It will output an error message to the console providing details of the exception.
Console.WriteLine($"An error occurred while loading the Excel file: {ex.Message}")
End Try
' Additional Notes:
' - Be sure that the Excel file path is correct, and the application has permissions to access it.
' - The use of a try-catch block helps in gracefully handling any runtime errors
' that may occur while attempting to load the Excel file.
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
// The following script demonstrates how to access an Excel worksheet from a workbook in C#.
// Please note that you need to have a reference to a library that provides Excel file manipulation capabilities.
// Libraries such as EPPlus, ClosedXML, or Interop.Excel can be used to achieve this functionality.
using System;
// Hypothetical library for Excel manipulation (replace with an actual library, e.g. EPPlus or ClosedXML)
using ExcelLibrary;
// It's assumed that 'ExcelLibrary' has a similar interface. Make sure to adjust according to the actual library used.
// Initialize and open the Excel workbook
// Note: Replace this example with actual initialization code based on the library you are using.
WorkBook workBook = new WorkBook(); // This should be replaced with actual loading code, e.g., WorkBook.LoadFromFile("path/to/file.xlsx");
// Attempt to access a specific worksheet from the workbook
WorkSheet workSheet = workBook.GetWorkSheet("Sheet1");
// Ensure that the worksheet was found and is not null
if (workSheet == null)
{
Console.WriteLine("The worksheet 'Sheet1' could not be found in the workbook.");
}
else
{
Console.WriteLine("Worksheet 'Sheet1' opened successfully.");
// Additional code for working with the worksheet can be added here
// For example, reading or writing data to the worksheet
}
// Key Points:
//
// 1. **Library Reference:** The code assumes the use of an Excel manipulation library.
// Make sure to replace `ExcelLibrary` with the actual library you are using, such as EPPlus, ClosedXML, Interop.Excel, etc.
//
// 2. **Object Initialization:** Ensure that `WorkBook` and `WorkSheet` objects are initialized correctly.
// The `WorkBook` should be loaded with an existing Excel file,
// and specific methods from the chosen library will be used to open the workbook.
//
// 3. **Null Check:** A null check is applied to ensure the worksheet was successfully retrieved.
// This is essential to handle cases where the worksheet might not be present.
//
// 4. **Namespace and Using Directives:** Ensure that necessary namespaces and using directives are included,
// especially those required for the specific library being used.
' The following script demonstrates how to access an Excel worksheet from a workbook in C#.
' Please note that you need to have a reference to a library that provides Excel file manipulation capabilities.
' Libraries such as EPPlus, ClosedXML, or Interop.Excel can be used to achieve this functionality.
Imports System
' Hypothetical library for Excel manipulation (replace with an actual library, e.g. EPPlus or ClosedXML)
Imports ExcelLibrary
' It's assumed that 'ExcelLibrary' has a similar interface. Make sure to adjust according to the actual library used.
' Initialize and open the Excel workbook
' Note: Replace this example with actual initialization code based on the library you are using.
Private workBook As New WorkBook() ' This should be replaced with actual loading code, e.g., WorkBook.LoadFromFile("path/to/file.xlsx");
' Attempt to access a specific worksheet from the workbook
Private workSheet As WorkSheet = workBook.GetWorkSheet("Sheet1")
' Ensure that the worksheet was found and is not null
If workSheet Is Nothing Then
Console.WriteLine("The worksheet 'Sheet1' could not be found in the workbook.")
Else
Console.WriteLine("Worksheet 'Sheet1' opened successfully.")
' Additional code for working with the worksheet can be added here
' For example, reading or writing data to the worksheet
End If
' Key Points:
'
' 1. **Library Reference:** The code assumes the use of an Excel manipulation library.
' Make sure to replace `ExcelLibrary` with the actual library you are using, such as EPPlus, ClosedXML, Interop.Excel, etc.
'
' 2. **Object Initialization:** Ensure that `WorkBook` and `WorkSheet` objects are initialized correctly.
' The `WorkBook` should be loaded with an existing Excel file,
' and specific methods from the chosen library will be used to open the workbook.
'
' 3. **Null Check:** A null check is applied to ensure the worksheet was successfully retrieved.
' This is essential to handle cases where the worksheet might not be present.
'
' 4. **Namespace and Using Directives:** Ensure that necessary namespaces and using directives are included,
' especially those required for the specific library being used.
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
// The following line of code assigns a specified value to a given cell within an Excel worksheet.
// It assumes that you have a reference to a 'worksheet' object from a library
// like EPPlus, ClosedXML, or similar that handles Excel files in C#.
// Ensure that the worksheet object is properly initialized,
// and a valid cell address, such as "A1" or "B2", is provided.
// Example setup (make sure to replace 'workSheet' and 'Cell Address' with actual instances and addresses):
workSheet.Cells["A1"].Value = "Sample Value";
// Explanation:
// - 'Cells' is a property used to access specific cells in the worksheet.
// - "A1" should be replaced with the actual cell address you intend to modify.
// - .Value is the property used to set or retrieve the value in that cell.
' The following line of code assigns a specified value to a given cell within an Excel worksheet.
' It assumes that you have a reference to a 'worksheet' object from a library
' like EPPlus, ClosedXML, or similar that handles Excel files in C#.
' Ensure that the worksheet object is properly initialized,
' and a valid cell address, such as "A1" or "B2", is provided.
' Example setup (make sure to replace 'workSheet' and 'Cell Address' with actual instances and addresses):
workSheet.Cells("A1").Value = "Sample Value"
' Explanation:
' - 'Cells' is a property used to access specific cells in the worksheet.
' - "A1" should be replaced with the actual cell address you intend to modify.
' - .Value is the property used to set or retrieve the value in that cell.
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;
// This code demonstrates loading an Excel file, modifying a specific cell, and saving the file.
try
{
// Load the Excel file named "sample.xlsx" into a WorkBook object.
WorkBook workBook = WorkBook.Load("sample.xlsx");
// Open the WorkSheet named "Sheet1" within the loaded WorkBook.
if (workBook.WorkSheets.Contains("Sheet1"))
{
WorkSheet workSheet = workBook.GetWorkSheet("Sheet1");
// Access the cell at position A1 in the WorkSheet and update its value to "new value".
workSheet["A1"].Value = "new value";
// Save the changes back to the Excel file.
workBook.SaveAs("sample.xlsx");
}
else
{
Console.WriteLine("Sheet1 not found in the workbook.");
}
}
catch (Exception ex)
{
// Handle any exceptions that may occur during file operations.
Console.WriteLine("An error occurred: " + ex.Message);
}
Imports IronXL
' This code demonstrates loading an Excel file, modifying a specific cell, and saving the file.
Try
' Load the Excel file named "sample.xlsx" into a WorkBook object.
Dim workBook As WorkBook = WorkBook.Load("sample.xlsx")
' Open the WorkSheet named "Sheet1" within the loaded WorkBook.
If workBook.WorkSheets.Contains("Sheet1") Then
Dim workSheet As WorkSheet = workBook.GetWorkSheet("Sheet1")
' Access the cell at position A1 in the WorkSheet and update its value to "new value".
workSheet("A1").Value = "new value"
' Save the changes back to the Excel file.
workBook.SaveAs("sample.xlsx")
Else
Console.WriteLine("Sheet1 not found in the workbook.")
End If
Catch ex As Exception
' Handle any exceptions that may occur during file operations.
Console.WriteLine("An error occurred: " & ex.Message)
End Try
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
// The code assigns a string value to a cell in a worksheet.
// Assuming workSheet is an object of a type that supports cell operations
// with StringValue, such as a library class for handling spreadsheet files.
// This may typically be part of a library like EPPlus, ClosedXML, or similar.
try
{
// Assign the value "4402-12" as a string to cell A1 in the worksheet.
workSheet["A1"].Value = "4402-12"; // Assuming 'Value' is the correct property to set in the library being used.
}
catch (Exception e)
{
// Log or handle exception if the operation fails
Console.WriteLine($"An error occurred while assigning the cell value: {e.Message}");
}
// Note: We assumed the presence of a try-catch block for error handling.
// The specific method/property to set a cell's value may vary depending on
// the library in use. Please refer to the library documentation for specifics.
' The code assigns a string value to a cell in a worksheet.
' Assuming workSheet is an object of a type that supports cell operations
' with StringValue, such as a library class for handling spreadsheet files.
' This may typically be part of a library like EPPlus, ClosedXML, or similar.
Try
' Assign the value "4402-12" as a string to cell A1 in the worksheet.
workSheet("A1").Value = "4402-12" ' Assuming 'Value' is the correct property to set in the library being used.
Catch e As Exception
' Log or handle exception if the operation fails
Console.WriteLine($"An error occurred while assigning the cell value: {e.Message}")
End Try
' Note: We assumed the presence of a try-catch block for error handling.
' The specific method/property to set a cell's value may vary depending on
' the library in use. Please refer to the library documentation for specifics.
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"
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;
// The IronXL library allows you to read and write Excel files without requiring Microsoft Excel installation.
// This script demonstrates loading an Excel file, modifying specific cell ranges, and saving the changes.
try
{
// Load the Excel file named "sample.xlsx".
// Ensure the file exists in the specified directory.
WorkBook workBook = WorkBook.Load("sample.xlsx");
// Open the worksheet named "Sheet1" from the loaded workbook.
// Verify that the sheet exists in the workbook.
WorkSheet workSheet = workBook.GetWorkSheet("Sheet1");
// Specify a range of cells from B2 to B9 (row-wise) and set their value to "new value".
// This updates each cell in the column B from the second row to the ninth row with "new value".
// Ensure the range is valid and within the bounds of the worksheet.
workSheet["B2:B9"].Value = "new value";
// Specify a range of cells from C3 to C7 (column-wise) and set their value to "new value".
// This updates each cell in the column C from the third row to the seventh row with "new value".
// Ensure the range is valid to prevent runtime errors.
workSheet["C3:C7"].Value = "new value";
// Save the modified workbook to "sample.xlsx".
// This will overwrite the existing file with the new changes.
// Verify you have the correct permissions and the file isn't in use.
workBook.SaveAs("sample.xlsx");
Console.WriteLine("Workbook successfully modified and saved.");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
// Note: Ensure you have write permissions to the file and its directory,
// and the file isn't open in another application to avoid IO exceptions.
Imports IronXL
' The IronXL library allows you to read and write Excel files without requiring Microsoft Excel installation.
' This script demonstrates loading an Excel file, modifying specific cell ranges, and saving the changes.
Try
' Load the Excel file named "sample.xlsx".
' Ensure the file exists in the specified directory.
Dim workBook As WorkBook = WorkBook.Load("sample.xlsx")
' Open the worksheet named "Sheet1" from the loaded workbook.
' Verify that the sheet exists in the workbook.
Dim workSheet As WorkSheet = workBook.GetWorkSheet("Sheet1")
' Specify a range of cells from B2 to B9 (row-wise) and set their value to "new value".
' This updates each cell in the column B from the second row to the ninth row with "new value".
' Ensure the range is valid and within the bounds of the worksheet.
workSheet("B2:B9").Value = "new value"
' Specify a range of cells from C3 to C7 (column-wise) and set their value to "new value".
' This updates each cell in the column C from the third row to the seventh row with "new value".
' Ensure the range is valid to prevent runtime errors.
workSheet("C3:C7").Value = "new value"
' Save the modified workbook to "sample.xlsx".
' This will overwrite the existing file with the new changes.
' Verify you have the correct permissions and the file isn't in use.
workBook.SaveAs("sample.xlsx")
Console.WriteLine("Workbook successfully modified and saved.")
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
' Note: Ensure you have write permissions to the file and its directory,
' and the file isn't open in another application to avoid IO exceptions.
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; // Import IronXL library to manipulate Excel files
// Load an existing Excel file named "sample.xlsx" into a WorkBook object
WorkBook workBook = WorkBook.Load("sample.xlsx");
// Access a specific WorkSheet named "Sheet1" within the WorkBook
WorkSheet workSheet = workBook.GetWorkSheet("Sheet1");
// Loop to write dynamic values into a specified range of cells.
// The loop iterates over rows 2 to 7.
for (int i = 2; i <= 7; i++)
{
// Write a dynamic value into column B for each row from 2 to 7.
workSheet["B" + i].Value = "Value" + i;
// Write a dynamic value into column D for each row from 2 to 7.
workSheet["D" + i].Value = "Value" + i;
}
// Save the changes made to the workbook back to the original file
workBook.SaveAs("sample.xlsx");
Imports IronXL ' Import IronXL library to manipulate Excel files
' Load an existing Excel file named "sample.xlsx" into a WorkBook object
Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
' Access a specific WorkSheet named "Sheet1" within the WorkBook
Private workSheet As WorkSheet = workBook.GetWorkSheet("Sheet1")
' Loop to write dynamic values into a specified range of cells.
' The loop iterates over rows 2 to 7.
For i As Integer = 2 To 7
' Write a dynamic value into column B for each row from 2 to 7.
workSheet("B" & i).Value = "Value" & i
' Write a dynamic value into column D for each row from 2 to 7.
workSheet("D" & i).Value = "Value" & i
Next i
' Save the changes made to the workbook back to the original file
workBook.SaveAs("sample.xlsx")
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
.
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
// Assuming that there is a 'workSheet' object which supports a 'Replace' method.
// Note: The actual object structure is not visible in the provided code snippet.
// The method below presumes the object belongs to a type that has a Replace method accepting old and new string values.
using System;
// Example class representing a worksheet (or similar object) with the Replace method
public class WorkSheet
{
private string content;
// Constructor to initialize content with a given string
public WorkSheet(string initialContent)
{
content = initialContent;
}
// Replaces all occurrences of oldValue with newValue in the content
public void Replace(string oldValue, string newValue)
{
// Check if the old value is null or empty, and return if so
if (string.IsNullOrEmpty(oldValue))
{
Console.WriteLine("The old value is null or empty.");
return;
}
// Check if content contains the old value and replace if it does
if (content.Contains(oldValue))
{
content = content.Replace(oldValue, newValue);
Console.WriteLine($"Replaced '{oldValue}' with '{newValue}'.");
}
else
{
Console.WriteLine($"The content does not contain '{oldValue}'.");
}
}
// Method to display the current content of the worksheet
public void DisplayContent()
{
Console.WriteLine($"Current content: {content}");
}
}
public class Program
{
public static void Main()
{
// Sample usage of the WorkSheet class
// Initial content of the worksheet
string initialContent = "This is the old value that needs to be replaced. The old value can be anywhere.";
// Create a WorkSheet instance with initial content
WorkSheet workSheet = new WorkSheet(initialContent);
// Replace occurrences of "old value" with "new value"
workSheet.Replace("old value", "new value");
// Display the updated content
workSheet.DisplayContent();
}
}
' Assuming that there is a 'workSheet' object which supports a 'Replace' method.
' Note: The actual object structure is not visible in the provided code snippet.
' The method below presumes the object belongs to a type that has a Replace method accepting old and new string values.
Imports System
' Example class representing a worksheet (or similar object) with the Replace method
Public Class WorkSheet
Private content As String
' Constructor to initialize content with a given string
Public Sub New(ByVal initialContent As String)
content = initialContent
End Sub
' Replaces all occurrences of oldValue with newValue in the content
Public Sub Replace(ByVal oldValue As String, ByVal newValue As String)
' Check if the old value is null or empty, and return if so
If String.IsNullOrEmpty(oldValue) Then
Console.WriteLine("The old value is null or empty.")
Return
End If
' Check if content contains the old value and replace if it does
If content.Contains(oldValue) Then
content = content.Replace(oldValue, newValue)
Console.WriteLine($"Replaced '{oldValue}' with '{newValue}'.")
Else
Console.WriteLine($"The content does not contain '{oldValue}'.")
End If
End Sub
' Method to display the current content of the worksheet
Public Sub DisplayContent()
Console.WriteLine($"Current content: {content}")
End Sub
End Class
Public Class Program
Public Shared Sub Main()
' Sample usage of the WorkSheet class
' Initial content of the worksheet
Dim initialContent As String = "This is the old value that needs to be replaced. The old value can be anywhere."
' Create a WorkSheet instance with initial content
Dim workSheet As New WorkSheet(initialContent)
' Replace occurrences of "old value" with "new value"
workSheet.Replace("old value", "new value")
' Display the updated content
workSheet.DisplayContent()
End Sub
End Class
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
// Assuming 'workSheet' is a proper object of a class handling spreadsheet functionalities,
// and 'RowIndex' is an integer representing the index of the row you want to modify.
// The following code aims to replace a specific string ("old value") with another string ("new value")
// in a particular row of an Excel-like worksheet.
if (workSheet != null) // Check if workSheet is not null to avoid NullReferenceException.
{
// Assuming RowIndex is within the range of available rows in workSheet
if (RowIndex >= 0 && RowIndex < workSheet.Rows.Count)
{
// Iterate through each cell in the specified row to perform the replacement
foreach (var cell in workSheet.Rows[RowIndex].Cells)
{
// Ensure the cell value is a string before attempting the replacement
if (cell.Value is string cellValue)
{
// Replace occurrences of "old value" with "new value" if found within the cell value.
cell.Value = cellValue.Replace("old value", "new value");
}
}
}
else
{
// Output a message indicating that the provided RowIndex is out of the valid range
Console.WriteLine("RowIndex is out of bounds.");
}
}
else
{
// Output a message indicating that the worksheet reference is null
Console.WriteLine("Worksheet is null.");
}
' Assuming 'workSheet' is a proper object of a class handling spreadsheet functionalities,
' and 'RowIndex' is an integer representing the index of the row you want to modify.
' The following code aims to replace a specific string ("old value") with another string ("new value")
' in a particular row of an Excel-like worksheet.
If workSheet IsNot Nothing Then ' Check if workSheet is not null to avoid NullReferenceException.
' Assuming RowIndex is within the range of available rows in workSheet
If RowIndex >= 0 AndAlso RowIndex < workSheet.Rows.Count Then
' Iterate through each cell in the specified row to perform the replacement
For Each cell In workSheet.Rows(RowIndex).Cells
' Ensure the cell value is a string before attempting the replacement
Dim tempVar As Boolean = TypeOf cell.Value Is String
Dim cellValue As String = If(tempVar, CStr(cell.Value), Nothing)
If tempVar Then
' Replace occurrences of "old value" with "new value" if found within the cell value.
cell.Value = cellValue.Replace("old value", "new value")
End If
Next cell
Else
' Output a message indicating that the provided RowIndex is out of the valid range
Console.WriteLine("RowIndex is out of bounds.")
End If
Else
' Output a message indicating that the worksheet reference is null
Console.WriteLine("Worksheet is null.")
End If
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
// This code snippet defines a Worksheet class with the capability to replace values in a specified column.
// It demonstrates the manipulation of a hypothetical worksheet data structure.
using System;
using System.Collections.Generic;
public class Worksheet
{
// Represents a simplified version of a worksheet with a collection of columns.
public List<List<string>> Columns { get; set; }
// Initializes the worksheet with a specified number of columns and rows.
public Worksheet(int numberOfColumns, int numberOfRows)
{
// Initialize the columns of the worksheet with empty strings.
Columns = new List<List<string>>(numberOfColumns);
for (int i = 0; i < numberOfColumns; i++)
{
Columns.Add(new List<string>(new string[numberOfRows]));
}
}
// Replaces all occurrences of `oldValue` with `newValue` in the specified column.
public void ReplaceInColumn(int columnIndex, string oldValue, string newValue)
{
// Check if the provided columnIndex is valid for the current worksheet.
if (columnIndex < 0
columnIndex >= Columns.Count)
{
throw new ArgumentOutOfRangeException(nameof(columnIndex), "Invalid column index.");
}
// Get the column at the specified index.
List<string> column = Columns[columnIndex];
// Iterate over each row in the column to perform the replacement.
for (int row = 0; row < column.Count; row++)
{
if (column[row] == oldValue)
{
column[row] = newValue; // Replace the old value with the new value.
}
}
}
}
// Example usage of the Worksheet class.
public static class Program
{
public static void Main()
{
// Create a worksheet with 3 columns and 5 rows
Worksheet workSheet = new Worksheet(3, 5);
// Populate the worksheet with some example data
workSheet.Columns[0] = new List<string> { "old value", "data1", "old value", "data3", "old value" };
workSheet.Columns[1] = new List<string> { "data4", "old value", "data6", "old value", "data8" };
workSheet.Columns[2] = new List<string> { "data9", "data10", "data11", "data12", "old value" };
int columnIndex = 0; // Specify the column to perform the replace operation
string oldValue = "old value";
string newValue = "new value";
// Perform replacement in the specified column
workSheet.ReplaceInColumn(columnIndex, oldValue, newValue);
// Output the modified columns
for (int i = 0; i < workSheet.Columns.Count; i++)
{
Console.WriteLine($"Column {i}: {string.Join(", ", workSheet.Columns[i])}");
}
}
}
' This code snippet defines a Worksheet class with the capability to replace values in a specified column.
' It demonstrates the manipulation of a hypothetical worksheet data structure.
Imports System
Imports System.Collections.Generic
Public Class Worksheet
' Represents a simplified version of a worksheet with a collection of columns.
Public Property Columns() As List(Of List(Of String))
' Initializes the worksheet with a specified number of columns and rows.
Public Sub New(ByVal numberOfColumns As Integer, ByVal numberOfRows As Integer)
' Initialize the columns of the worksheet with empty strings.
Columns = New List(Of List(Of String))(numberOfColumns)
For i As Integer = 0 To numberOfColumns - 1
Columns.Add(New List(Of String)(New String(numberOfRows - 1){}))
Next i
End Sub
' Replaces all occurrences of `oldValue` with `newValue` in the specified column.
Public Sub ReplaceInColumn(ByVal columnIndex As Integer, ByVal oldValue As String, ByVal newValue As String)
' Check if the provided columnIndex is valid for the current worksheet.
If columnIndex < 0 OrElse columnIndex >= Columns.Count Then
Throw New ArgumentOutOfRangeException(NameOf(columnIndex), "Invalid column index.")
End If
' Get the column at the specified index.
Dim column As List(Of String) = Columns(columnIndex)
' Iterate over each row in the column to perform the replacement.
For row As Integer = 0 To column.Count - 1
If column(row) = oldValue Then
column(row) = newValue ' Replace the old value with the new value.
End If
Next row
End Sub
End Class
' Example usage of the Worksheet class.
Public Module Program
Public Sub Main()
' Create a worksheet with 3 columns and 5 rows
Dim workSheet As New Worksheet(3, 5)
' Populate the worksheet with some example data
workSheet.Columns(0) = New List(Of String) From {"old value", "data1", "old value", "data3", "old value"}
workSheet.Columns(1) = New List(Of String) From {"data4", "old value", "data6", "old value", "data8"}
workSheet.Columns(2) = New List(Of String) From {"data9", "data10", "data11", "data12", "old value"}
Dim columnIndex As Integer = 0 ' Specify the column to perform the replace operation
Dim oldValue As String = "old value"
Dim newValue As String = "new value"
' Perform replacement in the specified column
workSheet.ReplaceInColumn(columnIndex, oldValue, newValue)
' Output the modified columns
For i As Integer = 0 To workSheet.Columns.Count - 1
Console.WriteLine($"Column {i}: {String.Join(", ", workSheet.Columns(i))}")
Next i
End Sub
End Module
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
// This code snippet demonstrates how to replace occurrences of a specified value
// in a defined range of an Excel worksheet with a new value using the EPPlus library.
// The example assumes you have the library correctly installed in your C# project.
using OfficeOpenXml; // Ensure the EPPlus library is included in your project.
using System;
public class ExcelModifier
{
// Entry point of the program
public static void Main()
{
// Path to the Excel file you want to modify
string filePath = "path_to_your_excel_file.xlsx";
// Load the Excel package (the wrapper for handling Excel files)
using (var package = new ExcelPackage(new System.IO.FileInfo(filePath)))
{
// Access the worksheet by name, ensure that the worksheet exists in the Excel file
ExcelWorksheet workSheet = package.Workbook.Worksheets["Sheet1"];
if (workSheet == null)
{
Console.WriteLine("Worksheet 'Sheet1' not found!");
return;
}
// Define the cell range where replacements will occur
string cellRange = "A1:B3"; // Example range to look for old values
string oldValue = "old value"; // The value to be replaced
string newValue = "new value"; // The value to replace with
// Iterate through each cell in the specified cell range
foreach (var cell in workSheet.Cells[cellRange])
{
// Check if the cell's value matches the old value (case-sensitive match)
if (cell.Value != null && cell.Value.ToString() == oldValue)
{
// Replace the matched old value with the new value
cell.Value = newValue;
}
}
// Save changes made to the Excel package
package.Save();
}
}
}
' This code snippet demonstrates how to replace occurrences of a specified value
' in a defined range of an Excel worksheet with a new value using the EPPlus library.
' The example assumes you have the library correctly installed in your C# project.
Imports OfficeOpenXml ' Ensure the EPPlus library is included in your project.
Imports System
Public Class ExcelModifier
' Entry point of the program
Public Shared Sub Main()
' Path to the Excel file you want to modify
Dim filePath As String = "path_to_your_excel_file.xlsx"
' Load the Excel package (the wrapper for handling Excel files)
Using package = New ExcelPackage(New System.IO.FileInfo(filePath))
' Access the worksheet by name, ensure that the worksheet exists in the Excel file
Dim workSheet As ExcelWorksheet = package.Workbook.Worksheets("Sheet1")
If workSheet Is Nothing Then
Console.WriteLine("Worksheet 'Sheet1' not found!")
Return
End If
' Define the cell range where replacements will occur
Dim cellRange As String = "A1:B3" ' Example range to look for old values
Dim oldValue As String = "old value" ' The value to be replaced
Dim newValue As String = "new value" ' The value to replace with
' Iterate through each cell in the specified cell range
For Each cell In workSheet.Cells(cellRange)
' Check if the cell's value matches the old value (case-sensitive match)
If cell.Value IsNot Nothing AndAlso cell.Value.ToString() = oldValue Then
' Replace the matched old value with the new value
cell.Value = newValue
End If
Next cell
' Save changes made to the Excel package
package.Save()
End Using
End Sub
End Class
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;
// Load an existing Excel workbook from the file "sample.xlsx".
WorkBook workBook = WorkBook.Load("sample.xlsx");
// Access the worksheet named "Sheet1" from the workbook.
WorkSheet workSheet = workBook.GetWorkSheet("Sheet1");
// Replace all occurrences of the string "old" with "new" throughout the entire worksheet.
workSheet.Replace("old", "new");
// Replace occurrences of the string "old" with "new" in a specific row, Row 6.
// Note: Row and column indices are zero-based in IronXL. Therefore, Row 6 is accessed using Rows[5].
workSheet.Rows[5].Replace("old", "new");
// Replace occurrences of the string "old" with "new" in a specific column, Column 5.
// Note: Column indices are zero-based in IronXL. Therefore, Column 5 is accessed using Columns[4].
workSheet.Columns[4].Replace("old", "new");
// Replace occurrences of the string "old" with "new" in a specific cell range, from cell A5 to H5.
workSheet["A5:H5"].Replace("old", "new");
// Save the changes back to the workbook. This will overwrite the existing file "sample.xlsx".
workBook.SaveAs("sample.xlsx");
Imports IronXL
' Load an existing Excel workbook from the file "sample.xlsx".
Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
' Access the worksheet named "Sheet1" from the workbook.
Private workSheet As WorkSheet = workBook.GetWorkSheet("Sheet1")
' Replace all occurrences of the string "old" with "new" throughout the entire worksheet.
workSheet.Replace("old", "new")
' Replace occurrences of the string "old" with "new" in a specific row, Row 6.
' Note: Row and column indices are zero-based in IronXL. Therefore, Row 6 is accessed using Rows[5].
workSheet.Rows(5).Replace("old", "new")
' Replace occurrences of the string "old" with "new" in a specific column, Column 5.
' Note: Column indices are zero-based in IronXL. Therefore, Column 5 is accessed using Columns[4].
workSheet.Columns(4).Replace("old", "new")
' Replace occurrences of the string "old" with "new" in a specific cell range, from cell A5 to H5.
workSheet("A5:H5").Replace("old", "new")
' Save the changes back to the workbook. This will overwrite the existing file "sample.xlsx".
workBook.SaveAs("sample.xlsx")
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 ReferenceFrequently Asked Questions
How do I get started with the IronXL library for writing Excel files in .NET?
To get started with IronXL, download the library and include it in your project. Import the library by using 'using IronXL' in your C# code.
How can I write a value to a specific cell in an Excel worksheet using IronXL?
To write a value to a specific cell, access the cell using its address, such as worksheet['A1'], and assign a value using the .Value property.
How do I assign a static value to a range of cells in Excel using IronXL?
To assign a static value to a range, specify the range using cell addresses, like worksheet['B2:C5'], and set the .Value property to your desired static value.
Can I write dynamic values to a range of cells in Excel with IronXL?
Yes, you can write dynamic values to a range using loops or custom logic. For example, you can iterate over cell addresses and assign dynamic values based on your requirements.
How can I replace existing cell values in an Excel worksheet using IronXL?
Use the Replace() method on the worksheet, row, column, or specified range to replace 'old value' with 'new value'.
What is the difference between using Value and StringValue in IronXL?
The .Value property may convert the assigned value to a type-specific format, while .StringValue assigns the value as a string, avoiding conversion.
How can I open and access a specific worksheet in an Excel file using IronXL?
Use WorkBook.Load('path/to/your/excel-file.xlsx') to load the file and workbook.GetWorkSheet('SheetName') to access a specific worksheet.
Is it necessary to save the Excel file after writing new values using IronXL?
Yes, you must save the Excel file after making changes by using the workbook.SaveAs('filename.xlsx') method to persist your changes.
How do I write a new value to replace an old value in a specific row using IronXL?
Access the row using worksheet.Rows[index] and then call the Replace() method with the old and new values.
Can I replace values in a specific column using IronXL?
Yes, access the column using worksheet.Columns['A'] and use the Replace() method to substitute old values with new ones in that column.