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#
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 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 Answers by the question author, which helps users to know the answer solved the author's problem.