Saving recalculated Excel file

落爺英雄遲暮 提交于 2020-01-16 03:07:43

问题


I need to remove all Excel formulas from my worksheet (replace formulas with its results) then save file. For example - instead B3+13 I want to have 2013-04-11 in cell when I open file using OpenXML

I have found this article http://office.microsoft.com/en-us/excel-help/replace-a-formula-with-its-result-HP010066258.aspx

It works - after saving there is no formula. I need the same effect in C#. I've tried many solutions in Internet but still no hope.

                string source = @"C:\Source\doc.xlsx";
            object Unknown = Type.Missing;

            Workbook doc = newApp.Workbooks.Open(
                source,
                 Unknown, 
                 Unknown, 
                 Unknown, 
                 Unknown, 
                 Unknown, 
                 Unknown, 
                 Unknown, 
                 Unknown, 
                 Unknown, 
                 Unknown, 
                 Unknown, 
                 Unknown, 
                 Unknown, 
                 Unknown);

            newApp.Calculation = Microsoft.Office.Interop.Excel.XlCalculation.xlCalculationManual;

            doc.ForceFullCalculation = true;
            newApp.CalculateFull();
            newApp.CalculateBeforeSave = true;

            doc.SaveAs("c:\\temp\\recalc.xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
            false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            doc.Close();

So what is the problem? Why I can see "=DY3+1" instead "2013-04-11"?


回答1:


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

using Excel = Microsoft.Office.Interop.Excel;
foreach (Excel.Worksheet ws in doc.Worksheets)
{
    Excel.Range targetRange = (Excel.Range)ws.UsedRange;
    targetRange.Copy(Type.Missing);
    targetRange.PasteSpecial(Excel.XlPasteType.xlPasteValues, 
        Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);
}

This duplicates the "Replace formulas with their calculated values" section of the document you posted. It's possible to select all the sheets and copy/paste special in Excel itself to get the results rather than the formulas, but I have had some issues working with grouped sheets through code.




回答2:


Calculating a formula retains both the formula and its result. If you want to overwrite the formula with its result value then you need to either:
- set its value to its value: Range.Value2=Range.value2
or use Copy and paste-special values



来源:https://stackoverflow.com/questions/16038256/saving-recalculated-excel-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!