基于C#的文档处理

环境是 C# + .NET Framework 4.0 + Visual Studio 2010 ,要实现对 Excel、Word、PowerPoint创建、读取、写入 以及转换为 PDF

这些操作可以完全通过 Microsoft Office Interop 来实现


🔧 一、准备工作

1. 安装与引用 Office Interop 库

你需要在项目中手动添加 COM 引用:

Visual Studio 2010 中:

复制代码
项目 → 添加引用 → COM → 搜索:

分别添加以下引用:

  • Microsoft Excel xx.0 Object Library
  • Microsoft Word xx.0 Object Library
  • Microsoft PowerPoint xx.0 Object Library
  • Microsoft Office xx.0 Object Library

⚠️ 其中 xx.0 取决于你的 Office 版本(例如 14.0 对应 Office 2010)。

添加后,命名空间如下:

csharp 复制代码
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;

📘 二、Excel 文档操作

1. 创建与写入 Excel 文件

csharp 复制代码
using Excel = Microsoft.Office.Interop.Excel;

public void CreateExcel()
{
    Excel.Application app = new Excel.Application();
    Excel.Workbook workbook = app.Workbooks.Add();
    Excel.Worksheet sheet = (Excel.Worksheet)workbook.ActiveSheet;

    sheet.Cells[1, 1] = "姓名";
    sheet.Cells[1, 2] = "成绩";
    sheet.Cells[2, 1] = "张三";
    sheet.Cells[2, 2] = "95";

    workbook.SaveAs(@"C:\test.xlsx");
    workbook.Close();
    app.Quit();
}

2. 读取 Excel 文件

csharp 复制代码
public void ReadExcel()
{
    Excel.Application app = new Excel.Application();
    Excel.Workbook workbook = app.Workbooks.Open(@"C:\test.xlsx");
    Excel.Worksheet sheet = (Excel.Worksheet)workbook.Sheets[1];

    string name = sheet.Cells[2, 1].Value.ToString();
    double score = sheet.Cells[2, 2].Value;

    MessageBox.Show($"{name} 的成绩是 {score}");

    workbook.Close(false);
    app.Quit();
}

3. Excel 转 PDF

csharp 复制代码
public void ExcelToPdf()
{
    Excel.Application app = new Excel.Application();
    Excel.Workbook workbook = app.Workbooks.Open(@"C:\test.xlsx");

    workbook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, @"C:\test.pdf");

    workbook.Close(false);
    app.Quit();
}

📗 三、Word 文档操作

1. 创建与写入 Word 文件

csharp 复制代码
using Word = Microsoft.Office.Interop.Word;

public void CreateWord()
{
    Word.Application app = new Word.Application();
    Word.Document doc = app.Documents.Add();

    Word.Paragraph para = doc.Content.Paragraphs.Add();
    para.Range.Text = "这是一个自动生成的Word文档。";
    para.Range.InsertParagraphAfter();

    doc.SaveAs(@"C:\test.docx");
    doc.Close();
    app.Quit();
}

2. 在 Word 中插入表格

csharp 复制代码
public void InsertTable()
{
    Word.Application app = new Word.Application();
    Word.Document doc = app.Documents.Open(@"C:\test.docx");

    Word.Range range = doc.Content;
    range.Collapse(Word.WdCollapseDirection.wdCollapseEnd);

    Word.Table table = doc.Tables.Add(range, 3, 3);
    table.Borders.Enable = 1;
    table.Cell(1, 1).Range.Text = "姓名";
    table.Cell(1, 2).Range.Text = "性别";
    table.Cell(1, 3).Range.Text = "成绩";

    table.Cell(2, 1).Range.Text = "张三";
    table.Cell(2, 2).Range.Text = "男";
    table.Cell(2, 3).Range.Text = "95";

    doc.Save();
    doc.Close();
    app.Quit();
}

3. 删除 Word 中的表格

csharp 复制代码
public void DeleteTables()
{
    Word.Application app = new Word.Application();
    Word.Document doc = app.Documents.Open(@"C:\test.docx");

    for (int i = doc.Tables.Count; i >= 1; i--)
    {
        doc.Tables[i].Delete();
    }

    doc.Save();
    doc.Close();
    app.Quit();
}

4. Word 转 PDF

csharp 复制代码
public void WordToPdf()
{
    Word.Application app = new Word.Application();
    Word.Document doc = app.Documents.Open(@"C:\test.docx");

    doc.ExportAsFixedFormat(@"C:\test.pdf", Word.WdExportFormat.wdExportFormatPDF);

    doc.Close();
    app.Quit();
}

📙 四、PowerPoint 文档操作

1. 创建 PowerPoint 幻灯片并写入内容

csharp 复制代码
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;

public void CreatePPT()
{
    PowerPoint.Application app = new PowerPoint.Application();
    PowerPoint.Presentation pres = app.Presentations.Add(MsoTriState.msoTrue);

    PowerPoint.Slide slide = pres.Slides.Add(1, PowerPoint.PpSlideLayout.ppLayoutText);
    slide.Shapes[1].TextFrame.TextRange.Text = "自动生成的PPT";
    slide.Shapes[2].TextFrame.TextRange.Text = "这是第二个文本框。";

    pres.SaveAs(@"C:\test.pptx");
    pres.Close();
    app.Quit();
}

2. 读取 PPT 文本内容

csharp 复制代码
public void ReadPPT()
{
    PowerPoint.Application app = new PowerPoint.Application();
    PowerPoint.Presentation pres = app.Presentations.Open(@"C:\test.pptx",
        MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);

    foreach (PowerPoint.Slide slide in pres.Slides)
    {
        foreach (PowerPoint.Shape shape in slide.Shapes)
        {
            if (shape.HasTextFrame == MsoTriState.msoTrue)
            {
                string text = shape.TextFrame.TextRange.Text;
                Console.WriteLine(text);
            }
        }
    }

    pres.Close();
    app.Quit();
}

3. PowerPoint 转 PDF

csharp 复制代码
public void PptToPdf()
{
    PowerPoint.Application app = new PowerPoint.Application();
    PowerPoint.Presentation pres = app.Presentations.Open(@"C:\test.pptx",
        MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);

    pres.SaveAs(@"C:\test.pdf", PowerPoint.PpSaveAsFileType.ppSaveAsPDF);
    pres.Close();
    app.Quit();
}
相关推荐
向上的车轮8 分钟前
为什么.NET(C#)转 Java 开发时常常在“吐槽”Java:checked exception
java·c#·.net
island131412 分钟前
CANN GE(图引擎)深度解析:计算图优化管线、内存静态规划与异构任务的 Stream 调度机制
开发语言·人工智能·深度学习·神经网络
坚持就完事了17 分钟前
Java中的集合
java·开发语言
魔芋红茶21 分钟前
Python 项目版本控制
开发语言·python
云小逸36 分钟前
【nmap源码解析】Nmap OS识别核心模块深度解析:osscan2.cc源码剖析(1)
开发语言·网络·学习·nmap
冰暮流星36 分钟前
javascript之二重循环练习
开发语言·javascript·数据库
风指引着方向37 分钟前
自定义算子开发入门:基于 CANN op-plugin 的扩展实践
开发语言
Fairy要carry42 分钟前
面试-GRPO强化学习
开发语言·人工智能
Liekkas Kono1 小时前
RapidOCR Python 贡献指南
开发语言·python·rapidocr
张张努力变强1 小时前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl