C#使用OpenXml读取Word、PPT、Excel文档内容

DocumentFormat.OpenXml是微软官方推出的一个操作Excel、Word、PPT文件的开源组件,因此它是免费的。以下是一些关于DocumentFormat.OpenXml的详细信息:

  1. 开源性质:DocumentFormat.OpenXml是一个开源项目,这意味着其源代码是公开的,并且允许开发者自由地使用、修改和分发。
  2. 功能:DocumentFormat.OpenXml提供了对Excel、Word、PPT等Office文档的底层操作能力,允许开发者以编程的方式对这些文档进行创建、编辑和修改。
  3. 版本:DocumentFormat.OpenXml有多个版本,其中最新的稳定版本是3.0.2。
  4. 性能与特点:虽然DocumentFormat.OpenXml提供了底层的操作能力,但使用它可能会比较复杂,因为它涉及到更多的底层细节和顺序限制。此外,由于其底层操作的特性,它并不总是能提供最高的性能。然而,对于那些需要精确控制文档结构和格式的开发者来说,DocumentFormat.OpenXml可能是一个不错的选择。

下面只做简单的对这几种格式的文件读取显示

使用NuGet搜索添加引用

DocumentFormat.OpenXml

运行调试代码(ppt或者word改下类名)

复制代码
List<string> list = MyExcelByOpenXml.Read(@"E:\资料\文档\xxx.xlsx");
if (list != null)
{
    for (int i = 0; i < list.Count; i++)
        Console.WriteLine(list[i]);
}

读取Excel

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

public class MyExcelByOpenXml
{
    public static List<string> Read(string filePath)
    {
        List<string> list = new List<string>();
        using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filePath, false))
        {
            // 获取工作表集合
            WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
            Sheets sheets = workbookPart.Workbook.Descendants<Sheets>().FirstOrDefault();

            foreach (Sheet sheet in sheets.Elements<Sheet>())
            {
                // 获取工作表内容
                WorksheetPart worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);

                // 获取工作表中的单元格
                var cells = worksheetPart.Worksheet.Descendants<Cell>();

                foreach (var cell in cells)
                {
                    // 获取单元格的值
                    string cellValue = GetCellValue(cell, workbookPart);
                    if (cellValue != null && cellValue != "")
                        list.Add(cellValue);
                    Console.WriteLine(cellValue);
                }
            }
        }
        return list;
    }
    private static string GetCellValue(Cell cell, WorkbookPart workbookPart)
    {
        string value = string.Empty;

        if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
        {
            int sharedStringIndex = int.Parse(cell.InnerText);
            value = workbookPart.SharedStringTablePart.SharedStringTable.ChildElements[sharedStringIndex].InnerText;
        }
        else if (cell.CellValue != null)
        {
            value = cell.CellValue.Text;
        }

        return value;
    }
}

读取Word

复制代码
using System;
using System.Collections.Generic;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

class MyWord
{
    // 读取所有内容,以段落分割
    public static List<string> Read(string fileName)
    {
        try
        {
            List<string> list = new List<string>();
            // 打开现有的Word文档
            using (WordprocessingDocument doc = WordprocessingDocument.Open(fileName, false))
            {
                // 获取文档的主体部分
                Body body = doc.MainDocumentPart.Document.Body;
                // 遍历所有段落并输出文本
                foreach (Paragraph para in body.Elements<Paragraph>())
                {
                    if (para.InnerText != null || para.InnerText != "")
                    {
                        list.Add(para.InnerText);
                        Console.WriteLine(para.InnerText);
                    }
                }
            }
            return list;
        }
        catch (Exception ex)
        {
            Console.WriteLine("读取Word失败:" + ex.Message);
            return null;
        }
    }
}

读取PPT

复制代码
using System;
using System.Collections.Generic;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;

class MyPPT
{
    // 读取所有内容,以段落分割
    public static List<string> Read(string fileName)
    {
        try
        {
            List<string> list = new List<string>();
            // 打开现有的ppt文档
            using (PresentationDocument ppt = PresentationDocument.Open(fileName, false))
            {
                // 获取文档的主体部分
                foreach (SlideId slideId in ppt.PresentationPart.Presentation.SlideIdList.Elements<SlideId>())
                {
                    // 获取幻灯片内容
                    SlidePart slidePart = (SlidePart)ppt.PresentationPart.GetPartById(slideId.RelationshipId);

                    // 获取幻灯片中的文本框
                    var textBoxes = slidePart.Slide.Descendants<DocumentFormat.OpenXml.Drawing.Text>();

                    foreach (var textBox in textBoxes)
                    {
                        Console.WriteLine(textBox.Text);
                        list.Add(textBox.Text);
                    }
                }
            }
            return list;
        }
        catch (Exception ex)
        {
            Console.WriteLine("读取Word失败:" + ex.Message);
            return null;
        }
    }
}
相关推荐
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
玩泥巴的3 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
word·二次开发·office·com互操作
大飞pkz3 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
QQ3596773453 天前
ArcGIS Pro实现基于 Excel 表格批量创建标准地理数据库(GDB)——高效数据库建库解决方案
数据库·arcgis·excel
唐青枫3 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
未来之窗软件服务3 天前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟