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;
        }
    }
}
相关推荐
bianguanyue2 小时前
SQLite密码修改故障排查:RSA加密随机性导致的数据库匹配问题
数据库·sqlite·c#
R-sz2 小时前
导出word并且插入图片
开发语言·c#·word
wáng bēn2 小时前
【java17】使用 Word 模板导出带替换符、动态表格和二维码的文档
java·word·itextpdf
小杨爱学习zb6 小时前
如何将公式图片转换为公式格式到wps/word里面
word
干净的坏蛋6 小时前
Microsoft Word 中 .doc 和 .docx 的区别
microsoft·word
CodeCraft Studio7 小时前
PPT处理控件Aspose.Slides教程:使用 C# 将 PPTX 转换为 EMF
c#·powerpoint·ppt·aspose·ppt格式转换
future14128 小时前
游戏开发日记7.12
数据结构·学习·c#·游戏开发
洁辉8 小时前
C# & .NET 面试深度复习指南
面试·c#·.net
码银8 小时前
基于Java的Markdown到Word文档转换工具的实现
java·word
_oP_i10 小时前
无法找到来自源 EdgeWebView,实际安装了,偶尔出现
c#