Search code examples
c#spreadsheetlight

SpreadsheetLight Updating excel file


I would like to read the excel file then find the correct row and add a value to that row But I am getting a error message file is used by another process.

I have add the file to the FileStream so I am not sure why I am getting this error?

System.IO.IOException: 'The process cannot access the file 'D:\repos\FHIRVal\Update.xlsx' because it is being used by another process.'

public static int UpdateExecelFile(string id, string status)
    {
        string FilePath = "D:\\repos\\FHIRVal\\Update.xlsx";


        using (SLDocument sl = new SLDocument())
        {
            FileStream fs = new FileStream(FilePath, FileMode.Open);
            SLDocument sheet = new SLDocument(fs, "Sheet");

            SLWorksheetStatistics stats = sheet.GetWorksheetStatistics();
            for (int j = 1; j < stats.EndRowIndex; j++)
            {
                var value = sheet.GetCellValueAsString(j, 2);

                if (value == id)
                {
                    Console.WriteLine(string.Format("{0} --- {1}", "Updating File", id));
                    string updateRow = string.Format("{0}{1}", "C",j);

                    sl.SetCellValue(updateRow, status);
                }

            }
            sheet.SaveAs(FilePath);
            fs.Close();
        }

Solution

  • I had the order incorrect I needed to have the fs.close before the sheetsaveas .