【C#】操作Execl和Word文件-2

发布于:2025-08-05 ⋅ 阅读:(12) ⋅ 点赞:(0)

在C#中,可以使用不同的库来操作Excel和Word文件,并执行增删改查等操作。以下是一些常用的方法:

操作Excel文件
使用EPPlus库
安装引用:
using OfficeOpenXml;

示例代码:
读取数据
插入新行
更新现有单元格
删除行

public void ExcelOperations()
{
    string filePath = "C:\\example.xlsx";

    using (var package = new ExcelPackage(new FileInfo(filePath)))
    {
        var worksheet = package.Workbook.Worksheets[0];

        // 读取数据
        Console.WriteLine("Data from A1: " + worksheet.Cells["A1"].Value);

        // 插入新行
        int lastRow = worksheet.Dimension.End.Row;
        worksheet.Cells[lastRow + 1, 1].Value = "New Row Data";
        
        // 更新现有单元格
        worksheet.Cells[2, 2].Value = "Updated Value";

        // 删除一行
        if (lastRow > 1)
        {
            worksheet.DeleteRow(lastRow);
        }

        package.Save();
    }
}

操作Word文件

使用Microsoft.Office.Interop.Word库

安装引用:
using Microsoft.Office.Interop.Word;

示例代码:
读取文本
插入新段落
更新现有文本
删除段落

public void WordOperations()
{
    string filePath = "C:\\example.docx";

    Application wordApp = new Application();
    Document doc;

    // 打开已存在的Word文件
    if (System.IO.File.Exists(filePath))
    {
        doc = wordApp.Documents.Open(filePath);
    }
    else
    {
        doc = wordApp.Documents.Add();
    }

    Range range;
    
    try
    {
        // 读取文本
        Console.WriteLine("First paragraph: " + doc.Paragraphs[1].Range.Text);

        // 插入新段落
        Word.Range newParagraphRange = doc.Content;
        newParagraphRange.InsertAfter("\nNew Paragraph Data");
        
        // 更新现有文本
        range = doc.Paragraphs[2].Range;
        range.Text += " Updated Text";
        
        // 删除一个段落
        if (doc.Paragraphs.Count > 1)
        {
            doc.Paragraphs[1].Range.Delete();
        }
    }
    finally
    {
        // 关闭文档并保存更改
        doc.SaveAs2(filePath);
        doc.Close();

        wordApp.Quit();
    }
}

通过这些示例代码,您可以执行Excel和Word文件的增删改查操作。注意,在使用Microsoft.Office.Interop.Word时,请确保已经安装了Office软件,并且需要管理员权限来运行相关程序。

 


网站公告

今日签到

点亮在社区的每一天
去签到