How to Replace Multiple Strings in an Excel Spreadsheet using C# .NET Framework
With the help of an API, we can edit the contents of our DOCX files directly with minimal code.
Using the below code examples, we can find and replace multiple text strings within a DOCX file (similar to how we might manually CTRL+F replace within the Word editor itself). All we need to do is configure our request parameters using the below example structure:
{
"InputFileBytes": "string",
"InputFileUrl": "string",
"ReplaceStrings": [
{
"MatchString": "string",
"ReplaceString": "string",
"MatchCase": true
}
]
}
In response, the API will return the encoding for our edited DOCX file.
To authorize our API call, we’ll just need a free-tier API key, which will allow us to make up to 800 calls per month with no additional commitments.
With our API key ready, we can start by installing the .NET SDK. Let’s run the following command in our Package Manager console to install via NuGet:
Install-Package Cloudmersive.APIClient.NET.DocumentAndDataConvert -Version 3.4.2
After that, let’s go ahead and call the function. Let’s configure our request with our file data, request parameters, and API key:
using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Api;
using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Client;
using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Model;
namespace Example
{
public class EditDocumentDocxReplaceMultiExample
{
public void main()
{
// Configure API key authorization: Apikey
Configuration.Default.AddApiKey("Apikey", "YOUR_API_KEY");
var apiInstance = new EditDocumentApi();
var reqConfig = new MultiReplaceStringRequest(); // MultiReplaceStringRequest | Document string replacement configuration input
try
{
// Replace multiple strings in Word DOCX document, return result
byte[] result = apiInstance.EditDocumentDocxReplaceMulti(reqConfig);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling EditDocumentApi.EditDocumentDocxReplaceMulti: " + e.Message );
}
}
}
}
Just like that, we now have a simple, free & low-code process for making programmatic changes to our DOCX content.