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;
        }
    }
}
相关推荐
William_cl9 小时前
C# ASP.NET MVC 数据验证实战:View 层双保险(Html.ValidationMessageFor + jQuery Validate)
后端·c#·asp.net·mvc
狮子不白10 小时前
C#WEB 防重复提交控制
开发语言·前端·程序人生·c#
Charles_go11 小时前
C#8、有哪些访问修饰符
java·前端·c#
yue00813 小时前
C# 求取整数的阶乘
java·开发语言·c#
企鹅侠客14 小时前
用AI写了一个Excel 批量插图工具
excel·excel批量插图
黑咩狗夜.cm15 小时前
Aspose.word实现表格每页固定表头、最后一行填满整个页面
开发语言·c#·word
code bean15 小时前
【C#笔记】Newtonsoft.Json 中 `[JsonIgnore]` 的作用详解
笔记·c#·json
gCode Teacher 格码致知15 小时前
Python教学基础:用Python和openpyxl结合Word模板域写入数据-由Deepseek产生
python·word
ccut 第一混16 小时前
用c# 制作一个扑克牌小游戏
开发语言·c#
IT老大哥16 小时前
局域网扫码枪/局域网二维码接收工具
c#·net