天天看點

OpenXML操作excel建立和删除工作表

一、建立工作表

         在 Open XML SDK 中,SpreadsheetDocument類表示 Excel 文檔包。若要打開并使用 Excel 文檔,要基于文檔建立SpreadsheetDocument 類的一個執行個體。調用 Open 方法之一。本示例代碼使用帶有需要兩個參數的簽名的 Open(String,Boolean) 方法。第一個參數采用表示要打開的文檔的完整路徑字元串。第二個參數是 true 或 false,如果此參數為true,表示是否要打開檔案以進行編輯。如果此參數為 false,則不會儲存對該文檔所做的任何更改。

        下面的 using 語句中顯示了調用 Open 方法的代碼。

// Open the document for editing.
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true)) 
{
   // Insert other code here.
}
           

        using 語句提供典型 .Open,.Save, .Close 序列的建議備選序列。它確定在遇到右大括号時會自動調用 Dispose 方法(OpenXML SDK 用來清理資源的内部方法)。using 語句後面的塊為 using 語句中建立或指定的對象設定範圍,在此示例中這個範圍就是 spreadsheet。

       SpreadsheetML 文檔的基本文檔結構由引用 Workbook中的工作表Sheets 和 Sheet 元素組成。将為每個 Worksheet 建立單獨的 XML 檔案。

       以 SpreadsheetDocument 文檔包形式打開文檔進行編輯後,代碼會使用 AddNewPart 方法向WorkbookPart 對象中添加一個新 WorksheetPart 對象。然後,它向WorksheetPart 對象中添加一個新 Worksheet 對象。

       以下是使用 C# 和 VisualBasic 編寫的完整示例代碼。

// Given a document name, inserts a new worksheet.
        public static void InsertWorksheet(string docName)
        {
            // Open the document for editing.
            using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
            {
                // Add a blank WorksheetPart.
                WorksheetPart newWorksheetPart=spreadSheet.WorkbookPart.AddNewPart<WorksheetPart>();
                newWorksheetPart.Worksheet = new Worksheet(new SheetData());
                Sheets sheets = spreadSheet.WorkbookPart.Workbook.GetFirstChild<Sheets>();
                string relationshipId = spreadSheet.WorkbookPart.GetIdOfPart(newWorksheetPart);

                // Get a unique ID for the new worksheet.
                uint sheetId = 1;
                if (sheets.Elements<Sheet>().Count() > 0)
                {
                    sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
                }
                // Give the new worksheet a name.
                string sheetName = "Sheet" + sheetId;
                // Append the new worksheet and associate it with the workbook.
                Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
                sheets.Append(sheet);
            }
        }
           

二、删除工作表

using System.Xml;
public static bool XLDeleteSheet(string fileName, string sheetToDelete)
{
   bool returnValue = false;
   using (SpreadsheetDocument xlDoc = SpreadsheetDocument.Open(fileName, true))
   {
      XmlDocument doc = new XmlDocument();
      doc.Load(xlDoc.WorkbookPart.GetStream());

      XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
      nsManager.AddNamespace("d", doc.DocumentElement.NamespaceURI);

      string searchString = string.Format("//d:sheet[@name='{0}']", sheetToDelete);
      XmlNode node = doc.SelectSingleNode(searchString, nsManager);
      if (node != null)
      {
         XmlAttribute relationAttribute = node.Attributes["r:id"];
         if (relationAttribute != null)
         {
            string relId = relationAttribute.Value;
            xlDoc.WorkbookPart.DeletePart(relId);
            node.ParentNode.RemoveChild(node);
            doc.Save(xlDoc.WorkbookPart.GetStream(FileMode.Create));
            returnValue = true;
          }
      }
   }
   return returnValue;
}
           

        在此程式中傳遞兩個參數:工作薄的完整路徑和要删除的工作表的名稱。然後使用 SpreadsheetDocument 對象的 Open 方法,以 Open XML 包的形式打開輸入檔案。接着,将工作薄中的内容載入 XML DOM 文檔。接着,使用 XmlNamespaceManager 對象并通過 d 限制符設定對預設 SpreadsheetML 命名空間的引用,來設定命名空間管理器。然後使用 //d:sheet 節點的名稱屬性搜尋指定工作表的文檔。對于所有比對的節點(如果存在),檢索關系 Id 并删除與該 Id 對應的工作表。最後,将更新的 SpreadsheetML 辨別儲存回主工作薄部件。

繼續閱讀