Home » excel » Save an excel file as values using C#

Save an excel file as values using C#

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have an excel file that has formulas in them. The formulas uses some functions that requires some third party add ins. I am trying to save the excel file as csv using the following code in C#. But the formula fields show up as an error. How can I save the formula fields as values and then save it in a csv.

 public static void SaveExcelFileAsCsvAllSheets(string fileName)
    {
        var app = new Microsoft.Office.Interop.Excel.Application();
        try
        {
            Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(fileName);
            app.DisplayAlerts = false;
            app.ScreenUpdating = false;
            int sheetCount = 1;
            foreach (Microsoft.Office.Interop.Excel.Worksheet sht in wb.Worksheets)
            {
                if (sht.Visible == XlSheetVisibility.xlSheetVisible)
                {
                    sht.Select();
                    wb.SaveAs(Path.GetDirectoryName(fileName) + @"\" + Path.GetFileNameWithoutExtension(fileName) + "-" + sheetCount.ToString() + ".csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV, AccessMode: XlSaveAsAccessMode.xlNoChange);
                    sheetCount++;
                }

            }

            wb.Close(false);
            app.DisplayAlerts = true;
            app.ScreenUpdating = true;
        }
        catch (Exception ex)
        {
            throw;
        }
        finally
        {
            app.Quit();

        }
    }
How to&Answers:

Select the range that contains your data, then copy and paste the values in place:

using Excel = Microsoft.Office.Interop.Excel;
Excel.Range targetRange = (Excel.Range)CurrentSheet.UsedRange;
targetRange.Copy(Type.Missing);
targetRange.Paste(Excel.XlPasteType.xlPasteValues, 
    Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);