Search code examples
c#excellinq-to-excel

Entering value into Excel sheet at particular location only thru linq to excel in c#


My Excel sheet is as below:

Id   Name  Status
1    XYZ
2    ABC
3    BB
1    Yz

What I am trying to do is to write Checked in the status column whose Id is 1 from my C# application.

I thought of doing this through Linq to Excel. But I am not getting anything positive in this direction.

Can anyone guide me properly.

Thanks.


Solution

  • You are out of luck here, as Linq-To-Excel does not write to spreadsheets (reference). The only option you have is to strongly type your queries, modifiy the results in memory and save them as a .csv to your harddisk - or use another 3rd party library to write the changes back to the excel file.

    public class Demo
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Status { get; set; }
    }
    
    string pathToExcelFile = @"path\to\file.xslx";  
    string sheetName = "Tabelle1";
    
    var excelFile = new ExcelQueryFactory(pathToExcelFile);
        //strongly type the result
    Demo rowToUpdate = (from xc in excelFile.Worksheet<Demo>(sheetName) 
                       where xc.ID == 1
                       select xc).FirstOrDefault();
        //update retrieved record
    rowToUpdate.Status = "Active";
        //output in linqpad
    rowToUpdate.Dump();
        //no submitchanges or save method available :(