What is the best way to store XML data in an Excel file

后端 未结 3 1556
说谎
说谎 2020-12-16 05:51

I am looking for a way to store XML data in an Excel file. The data should be completely hidden to the user, it should not be in a cell or comment, even hidden. Also, the da

3条回答
  •  星月不相逢
    2020-12-16 06:24

    I had the same issue and here is my code to deal with it, using Microsoft's Custom XML Parts. (You may find all the necessary explanations in my comments in the code).

    //Deletes all the previously added parts and adds a new part 
    //containing the string argument which has to be in XML format. 
    
    
    public void addCustomXMLPart(string test)
    {
        IEnumerator e = Xlworkbook.CustomXMLParts.GetEnumerator();
        e.Reset();
        CustomXMLPart p;
        //The !p.BuiltIn is because before our customXMLPart there are some
        // Excel BuiltIns of them and if we try to delete them we will get an exception.
        while (e.MoveNext())
        {
            p = (CustomXMLPart)e.Current;
            if (p != null && !p.BuiltIn) 
                p.Delete();
        }
        Xlworkbook.CustomXMLParts.Add(test, Type.Missing);
    }
    

    About the xlworkbook object used above:

    using Excel = Microsoft.Office.Interop.Excel;
    
    Excel.Workbook XlWorkbook = (Excel.Workbook)
      (Excel.Application)Marshal.GetActiveObject("Excel.Application")).ActiveWorkbook;
    

提交回复
热议问题