为什么不能超越实例而不退出

问题描述 投票:0回答:1

我试图从一堆excel文件中删除命名范围。

代码运行时抛出以下异常:

“索引无效。(HRESULT异常:0x8002000B(DISP_E_BADINDEX))”

尝试了我能想到的一切,但excel实例不会放弃!

请参阅下面粘贴的代码。 Interop不亚于一场可怕的噩梦! :(

enter image description here

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Excel = Microsoft.Office.Interop.Excel;
    using System.IO;
    using System.Diagnostics;
    using System.Runtime.InteropServices;

    namespace excel_delete_nr
    {
        class Program
        {
            static void Main(string[] args)
            {

                String tp_folder = @"C:\tp";
                String[] tps = Directory.GetFiles(tp_folder);

                foreach (String m in tps)
                {

                   var xlApp = new Excel.Application();
                   var xlWorkbooks = xlApp.Workbooks;
                   var xlWorkbook = xlWorkbooks.Open(m);


                    var ranges = xlWorkbook.Names;
                    int leftoveritems = ranges.Count;


                    while (leftoveritems > 0)
                    {
                        int i = 1;
                        try
                        {
                            while (i <= leftoveritems)
                            {
                                xlWorkbook.Names.Item(i).Delete();
                                //System.Windows.Forms.MessageBox.Show(i + " deleted.");
                                i++;
                            }
                        }
                        catch (Exception ex)
                        {
                             Console.WriteLine(ex.Message);
                        }

                        ranges = xlWorkbook.Names;
                        leftoveritems = ranges.Count;
                    }



                    xlWorkbook.Save();
                    xlWorkbook.Close();
                    xlWorkbooks.Close();
                    xlApp.Quit();

                    Marshal.ReleaseComObject(ranges);
                    Marshal.ReleaseComObject(xlWorkbook);
                    Marshal.ReleaseComObject(xlWorkbooks);
                    Marshal.ReleaseComObject(xlApp);

                }
            }
        }
    }
c# excel-interop
1个回答
1
投票

我使用下面的代码。使用Interop时必须非常小心。 但是如果你有这么简单的任务,如果你知道你的所有文件都是新的格式(了解Open XML),那么我将使用OpenXML解决方案,你根本不需要使用Excel,而且速度要快得多。检查下面

using System;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Runtime.InteropServices;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Which solution to use?\n1  - for running Excel or \n2 - for using OpenXML");
            var result = Console.ReadLine();
            if (string.IsNullOrWhiteSpace(result)) return;

            String tp_folder = @"c:\tp\";
            String[] tps = Directory.GetFiles(tp_folder);

            if (result == "1")
            {
                DeleteNamesWithExcelApp(tps);
            }
            else if (result == "2")
            {
                var cls = new OpenXmlSolution();
                foreach (String m in tps)
                {
                    cls.RemoveNames(m);
                }
            }

            Console.WriteLine("Done");
            Console.ReadLine();
        }

        public static void DeleteNamesWithExcelApp(String[] tps)
        {

            Excel.Workbooks xlWorkbooks = null;
            Excel.Workbook xlWorkbook = null;
            Excel.Names ranges = null;

            var xlApp = new Excel.Application();
            try
            {
                foreach (String m in tps)
                {
                    xlWorkbooks = xlApp.Workbooks;
                    xlWorkbook = xlWorkbooks.Open(m);
                    ranges = xlWorkbook.Names;
                    int leftoveritems = ranges.Count;

                    Excel.Name name = null;
                    try
                    {
                        for (int i = leftoveritems; i >= 1; i--)
                        {
                            name = xlWorkbook.Names.Item(i);
                            name.Delete();
                            if (name != null) Marshal.ReleaseComObject(name);
                            name = null;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        if (name != null) Marshal.ReleaseComObject(name);
                    }
                    if (xlWorkbook != null)
                    {
                        xlWorkbook.Close(true);
                        Marshal.ReleaseComObject(xlWorkbook);
                        xlWorkbook = null;
                    }
                    if (xlWorkbooks != null) Marshal.ReleaseComObject(xlWorkbooks);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (ranges != null) Marshal.ReleaseComObject(ranges);
                if (xlWorkbook != null) Marshal.ReleaseComObject(xlWorkbook);
                if (xlWorkbooks != null) Marshal.ReleaseComObject(xlWorkbooks);
                if (xlApp != null)
                {
                    xlApp.Quit();
                    Marshal.ReleaseComObject(xlApp);
                    xlApp = null;
                }
            }
        }
    }
}

这是我更喜欢的OpenXML解决方案。我真的不知道它与旧的xls文件的行为方式。

using DocumentFormat.OpenXml.Packaging;
using System.Linq;

namespace ConsoleApp3
{
    public class OpenXmlSolution
    {
        public void RemoveNames(string fullPathToFile)
        {            
            using (SpreadsheetDocument document = SpreadsheetDocument.Open(fullPathToFile, true))
            {
                WorkbookPart wbPart = document.WorkbookPart;
                var numOfNames = wbPart.Workbook.DefinedNames.Count();
                if (numOfNames == 0) return;
                for (int i = numOfNames -1 ; i >= 0; i--)
                {
                    wbPart.Workbook.DefinedNames.ChildElements[i].Remove();
                }                
                wbPart.Workbook.Save();                
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.