3

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();

        }
    }

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.