【问题标题】:C# - Having trouble with Excel/InteropServices Replace MethodC# - Excel/InteropServices 替换方法有问题
【发布时间】:2016-02-10 06:39:05
【问题描述】:

所以搜索返回了一些关于如何使用 Replace 方法的结果,但我还没有得到任何工作。希望你们能帮助我指出正确的方向!

这就是我所拥有的。调用 Replace 方法时出现错误。我怀疑我在 Range 上做错了什么,但不确定。

private Process DoExcelWork(Process excelProc, string filePath)
{
    // Initialize Excel Application
    Excel.Application excelApp = new Excel.Application();
    excelApp.Visible = false;

    // Get the process
    Process[] possibleProcesses = Process.GetProcessesByName("Excel");
    excelProc = possibleProcesses[0];

    // Empty Object for optional arguments
    object optional = System.Reflection.Missing.Value;

    Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(filePath, optional, optional, optional, optional, optional, optional, optional, optional, optional, optional, optional, optional, optional, optional);

    // Seems to be necessary to do stuff to the file
    excelWorkbook.VBProject.References.AddFromGuid("{0002E157-0000-0000-C000-000000000046}", 5, 3);

    foreach (Excel.Worksheet excelWorksheet in excelWorkbook.Worksheets)
    {
        Excel.Range lastCell = excelWorksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, optional);
        Excel.Range excelRange = excelWorksheet.get_Range("A1", lastCell);

        excelRange.Replace("Blue", "Red", Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, false, optional, optional, optional);
    }                   

    excelWorkbook.Save();
    excelWorkbook.Close(0);

    // Quit Excel 
    excelApp.Quit();

    // Release
    NAR(excelApp);

    return excelProc;
} 

这是错误:

System.Runtime.InteropServices.COMException (0x800706BE):远程 过程调用失败。 (来自 HRESULT 的异常:0x800706BE)在 System.RuntimeType.ForwardCallToInvokeMember(字符串成员名称, BindingFlags 标志、对象目标、Int32[] aWrapperTypes、MessageData& msgData)在 Microsoft.Office.Interop.Excel.Range.Replace(对象什么, 对象替换、对象 LookAt、对象 SearchOrder、对象 MatchCase、对象 MatchByte、对象 SearchFormat、对象 替换格式)

【问题讨论】:

    标签: c# asp.net excel excel-interop


    【解决方案1】:

    所以我从来没有没有让这个工作。我怀疑 Microsoft not supporting 这种服务器端自动化与它有关。

    我最终做了一个解决方法,我遍历每个单元格并手动更新值(如果满足搜索条件)。就我而言,我只是在寻找其中有公式的单元格,所以我也做了一些其他的事情。但这是我最终的结果:

    // Initialize Excel Application
    Excel.Application excelApp = null;
    excelApp = new Excel.Application();
    excelApp.Visible = false;
    excelApp.DisplayAlerts = false;
    
    // Get the process. Not as precise as would like, but probably the best we can get from an .ASP call
    Process[] possibleProcesses = Process.GetProcessesByName("Excel");
    excelProc = possibleProcesses[0];
    
    // Object for optional arguments when creating Excel Workbook
    object optional = System.Reflection.Missing.Value;
    
    Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(filePath, optional, optional, optional, optional, optional, optional, optional, optional, optional, optional, optional, optional, optional, optional);
    excelWorkbook.CheckCompatibility = false;
    excelWorkbook.DoNotPromptForConvert = true;
    
    // Create array with Custom Properties of workbook
    dynamic properties = excelWorkbook.CustomDocumentProperties;
    
    // Iterate through each worksheet in the workbook
    foreach (Excel.Worksheet excelWorksheet in excelWorkbook.Worksheets)
    {
        // Checking to see if any cells are being used. If no cells are used, setting ACTUAL used range causes an error.
        if (excelWorksheet.UsedRange.Cells.Count >=1)
        {
            try
            {
                // Because these sheets have thousands of edited (but unused) cells, can't use UsedRange without major performance issue. Getting last used cell manually.
                int lastRow = 1;
                int lastCol = 1;
                try
                {
                    lastRow = excelWorksheet.Cells.Find("*", excelWorksheet.get_Range("IV65536", optional), Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlPrevious, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Row;
                    lastCol = excelWorksheet.Cells.Find("*", excelWorksheet.get_Range("IV65536", optional), Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByColumns, Excel.XlSearchDirection.xlPrevious, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Column;
                }
                catch { }
    
                Excel.Range excelRange = excelWorksheet.get_Range(excelWorksheet.Cells[1, 1], excelWorksheet.Cells[lastRow, lastCol]);
    
                // Creating array of cells in range, because search operations are faster on array than on cells.
                dynamic cells = excelRange.Cells;
    
                string cellAddress = "";
                string cellFormula = "";
                string formulaParameter = "";
                int parameterLength = 0;
    
                // Search array for cells that have functions. If a function exists, replace it with the value that should be returned from the function.
                foreach (dynamic c in cells)
                {
                    if (c.HasFormula())
                    {
                        cellFormula = c.formula;
                        cellAddress = c.address.Replace("$", "");
    
                        if ((cellFormula.Length > 50) && (cellFormula.Substring(0, 50) == "=YOURCUSTOMEXCELFUNCTIONHERE"))
                        {
                            // Get custom functions, replace functions with the values returned from those functions
                            parameterLength = cellFormula.Substring(52).Length;
                            formulaParameter = cellFormula.Substring(52, parameterLength - 2);
    
                            foreach (dynamic p in properties)
                            {
                                if (p.name == formulaParameter)
                                {
                                    excelWorksheet.get_Range(cellAddress, optional).Value2 = p.Value;
                                }
                            }
                        }
                        else
                        {
                            // Get non-custom functions, replace functions with the values returned from those functions                                                       
                            excelWorksheet.get_Range(cellAddress, optional).Value2 = c.Value2;
                        }
                    }
                }
            }
            catch { }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 2011-11-24
      相关资源
      最近更新 更多