Writing In to Excel File

Nitin Sharma [NTSA] 5 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

Microsoft 365 and Office | Development | Other
Developer technologies | .NET | Other
Developer technologies | C#
Developer technologies | 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.
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,596 Reputation points Volunteer Moderator
    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 
    }
    

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.