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 标识保存回主工作薄部件。




  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值