Writing In to Excel File

Nitin Sharma [NTSA] 0 Reputation points
2023-04-05T11:06:16.7+00:00

How can I write to multiple specific cells in same column in Excel with C#, OleDb? In below file I want to write in cells D4,D5...(yellow cells) from my data source. User's image

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,447 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,362 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
3,570 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,196 Reputation points
    2023-04-05T16:52:42.27+00:00

    My advice is to use the free NuGet package SpreadSheetLight. In the following code sample, the list parameter can be any type.

    public static (bool success, Exception exception) InsertColumnData(
        string fileName, 
        int row, 
        int column, 
        List<string> list)
    {
        try
        {
            using (var document = new SLDocument(fileName, "Sheet1"))
            {
                for (int index = 0; index < list.Count; index++)
                {
                    document.SetCellValue(SLConvert.ToCellReference(row, column), list[index]);
                    
                    row++;
                }
    
                document.Save();
    
                return (true, null);
            }
        }
        catch (Exception exception)
        {
            return (false, exception);
        }
    }
    

    Usage kept simple

    var (success, exception) = InsertColumnData(
        "SomeFile.xlsx", 4,5, new List<string>()
    {
        "A", "B", "C", "D",
    });
    
    if (success)
    {
        // done
    }else if (exception != null)
    {
        // inspect 
    }