c# openxml 删除xlsx、xls的外链

要删除一个 Excel 文件(.xlsx)中的外部链接(external links),你可以使用 OpenXML SDK。外部链接通常包含在 `externalReferences` 元素中。以下是一个简单的 C# 代码示例,演示如何使用 OpenXML SDK 删除外部链接:

cs 复制代码
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

class Program
{
    static void Main()
    {
        string filePath = "your_file_path.xlsx";

        // 备份文件,以防需要还原
        string backupFilePath = "backup_file_path.xlsx";
        System.IO.File.Copy(filePath, backupFilePath, true);

        // 删除外部链接
        RemoveExternalLinks(filePath);

        Console.WriteLine("External links removed successfully.");
    }

    static void RemoveExternalLinks(string filePath)
    {
        using (SpreadsheetDocument spreadsheetDoc = SpreadsheetDocument.Open(filePath, true))
        {
            WorkbookPart workbookPart = spreadsheetDoc.WorkbookPart;

            // 删除 externalReferences 元素
            ExternalReferences externalReferences = workbookPart.Workbook.Descendants<ExternalReferences>().FirstOrDefault();
            if (externalReferences != null)
            {
                externalReferences.Remove();
            }

            // 保存更改
            workbookPart.Workbook.Save();
        }
    }
}

请确保将文件路径替换为你实际的文件路径。此代码将备份原始文件,并在原始文件上删除外部链接。如果需要还原,可以使用备份文件。记得在使用此代码前备份你的数据,以免不小心删除了重要的信息。

对于删除 Excel 文件(.xls)中的外部链接,你需要使用 NPOI(一个用于处理 Office 文件的开源库)或其他类似的库,因为 OpenXML SDK 主要用于处理 Office 2007及更高版本(.xlsx)的文件。

以下是使用 NPOI 的示例代码,用于删除 .xls 文件中的外部链接:

cs 复制代码
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "your_file_path.xls";

        // 备份文件,以防需要还原
        string backupFilePath = "backup_file_path.xls";
        File.Copy(filePath, backupFilePath, true);

        // 删除外部链接
        RemoveExternalLinks(filePath);

        Console.WriteLine("External links removed successfully.");
    }

    static void RemoveExternalLinks(string filePath)
    {
        using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
        {
            HSSFWorkbook workbook = new HSSFWorkbook(fileStream);

            // 删除外部链接
            workbook.ExternalLinksTable.RemoveAggregate();

            // 保存更改
            workbook.Write(fileStream);
        }
    }
}

请确保将文件路径替换为你实际的文件路径。这段代码将备份原始文件并在原始文件上删除外部链接。如果需要还原,可以使用备份文件。同样,请在使用此代码之前备份你的数据,以免不小心删除了重要的信息。

相关推荐
小码编匠18 小时前
WPF 中的高级交互通过右键拖动实现图像灵活缩放
后端·c#·.net
唐青枫1 天前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez20101 天前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
葡萄城技术团队2 天前
从100秒到10秒的性能优化,你真的掌握 Excel 的使用技巧了吗?
excel
mudtools2 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫2 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools3 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
大飞pkz3 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
QQ3596773453 天前
ArcGIS Pro实现基于 Excel 表格批量创建标准地理数据库(GDB)——高效数据库建库解决方案
数据库·arcgis·excel
唐青枫3 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net