最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#中操作Office文檔的完整教程

 更新時間:2025年10月29日 09:59:16   作者:yz123lucky  
這篇文章介紹了如何在C#中使用Microsoft Office Interop組件來操作Word、Excel和PowerPoint文檔,包括創(chuàng)建、讀取、修改、插入表格、添加圖表、轉換為PDF等操作,同時,還提供了注意事項、常見問題解決方法和部署注意事項,需要的朋友可以參考下

環(huán)境準備

1. 安裝Microsoft Office Interop組件

在Visual Studio 2010中添加引用:

  • 右鍵項目 → 添加引用 → COM標簽頁
  • 選擇以下組件:
    • Microsoft Word 14.0 Object Library
    • Microsoft Excel 14.0 Object Library
    • Microsoft PowerPoint 14.0 Object Library

2. 必要的using語句

using System;
using System.IO;
using System.Runtime.InteropServices;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;

Word文檔操作

1. 創(chuàng)建Word文檔

public class WordDocumentHelper
{
    /// <summary>
    /// 創(chuàng)建新的Word文檔
    /// </summary>
    public static void CreateWordDocument(string filePath)
    {
        Word.Application wordApp = null;
        Word.Document doc = null;
        
        try
        {
            // 創(chuàng)建Word應用程序實例
            wordApp = new Word.Application();
            wordApp.Visible = false; // 不顯示W(wǎng)ord窗口
            
            // 創(chuàng)建新文檔
            object missing = System.Reflection.Missing.Value;
            doc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
            
            // 添加標題
            Word.Paragraph titlePara = doc.Paragraphs.Add(ref missing);
            titlePara.Range.Text = "這是標題";
            titlePara.Range.Font.Size = 24;
            titlePara.Range.Font.Bold = 1;
            titlePara.Range.Font.Color = Word.WdColor.wdColorBlue;
            titlePara.Range.Font.Name = "微軟雅黑";
            titlePara.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            titlePara.Range.InsertParagraphAfter();
            
            // 添加正文
            Word.Paragraph contentPara = doc.Paragraphs.Add(ref missing);
            contentPara.Range.Text = "這是正文內容,可以設置不同的字體樣式。";
            contentPara.Range.Font.Size = 12;
            contentPara.Range.Font.Color = Word.WdColor.wdColorBlack;
            contentPara.Range.Font.Name = "宋體";
            contentPara.Range.InsertParagraphAfter();
            
            // 添加帶顏色的文本
            Word.Paragraph colorPara = doc.Paragraphs.Add(ref missing);
            colorPara.Range.Text = "這是紅色文本";
            colorPara.Range.Font.Size = 14;
            colorPara.Range.Font.Color = Word.WdColor.wdColorRed;
            colorPara.Range.Font.Italic = 1;
            colorPara.Range.InsertParagraphAfter();
            
            // 保存文檔
            object fileName = filePath;
            doc.SaveAs2(ref fileName);
            
            Console.WriteLine("Word文檔創(chuàng)建成功: " + filePath);
        }
        catch (Exception ex)
        {
            Console.WriteLine("創(chuàng)建Word文檔時出錯: " + ex.Message);
            throw;
        }
        finally
        {
            // 關閉文檔和應用程序
            if (doc != null)
            {
                doc.Close();
                Marshal.ReleaseComObject(doc);
            }
            if (wordApp != null)
            {
                wordApp.Quit();
                Marshal.ReleaseComObject(wordApp);
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}

2. 讀取Word文檔

public class WordDocumentHelper
{
    /// <summary>
    /// 創(chuàng)建新的Word文檔
    /// </summary>
    public static void CreateWordDocument(string filePath)
    {
        Word.Application wordApp = null;
        Word.Document doc = null;
        
        try
        {
            // 創(chuàng)建Word應用程序實例
            wordApp = new Word.Application();
            wordApp.Visible = false; // 不顯示W(wǎng)ord窗口
            
            // 創(chuàng)建新文檔
            object missing = System.Reflection.Missing.Value;
            doc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
            
            // 添加標題
            Word.Paragraph titlePara = doc.Paragraphs.Add(ref missing);
            titlePara.Range.Text = "這是標題";
            titlePara.Range.Font.Size = 24;
            titlePara.Range.Font.Bold = 1;
            titlePara.Range.Font.Color = Word.WdColor.wdColorBlue;
            titlePara.Range.Font.Name = "微軟雅黑";
            titlePara.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            titlePara.Range.InsertParagraphAfter();
            
            // 添加正文
            Word.Paragraph contentPara = doc.Paragraphs.Add(ref missing);
            contentPara.Range.Text = "這是正文內容,可以設置不同的字體樣式。";
            contentPara.Range.Font.Size = 12;
            contentPara.Range.Font.Color = Word.WdColor.wdColorBlack;
            contentPara.Range.Font.Name = "宋體";
            contentPara.Range.InsertParagraphAfter();
            
            // 添加帶顏色的文本
            Word.Paragraph colorPara = doc.Paragraphs.Add(ref missing);
            colorPara.Range.Text = "這是紅色文本";
            colorPara.Range.Font.Size = 14;
            colorPara.Range.Font.Color = Word.WdColor.wdColorRed;
            colorPara.Range.Font.Italic = 1;
            colorPara.Range.InsertParagraphAfter();
            
            // 保存文檔
            object fileName = filePath;
            doc.SaveAs2(ref fileName);
            
            Console.WriteLine("Word文檔創(chuàng)建成功: " + filePath);
        }
        catch (Exception ex)
        {
            Console.WriteLine("創(chuàng)建Word文檔時出錯: " + ex.Message);
            throw;
        }
        finally
        {
            // 關閉文檔和應用程序
            if (doc != null)
            {
                doc.Close();
                Marshal.ReleaseComObject(doc);
            }
            if (wordApp != null)
            {
                wordApp.Quit();
                Marshal.ReleaseComObject(wordApp);
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}

3. 在Word中插入表格

/// <summary>
/// 在Word文檔中插入表格
/// </summary>
public static void InsertTableInWord(string filePath)
{
    Word.Application wordApp = null;
    Word.Document doc = null;
    
    try
    {
        wordApp = new Word.Application();
        wordApp.Visible = false;
        
        object missing = System.Reflection.Missing.Value;
        doc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
        
        // 添加標題
        Word.Paragraph para = doc.Paragraphs.Add(ref missing);
        para.Range.Text = "員工信息表";
        para.Range.Font.Size = 16;
        para.Range.Font.Bold = 1;
        para.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
        para.Range.InsertParagraphAfter();
        
        // 插入表格 (5行3列)
        Word.Range range = doc.Paragraphs[doc.Paragraphs.Count].Range;
        Word.Table table = doc.Tables.Add(range, 5, 3, ref missing, ref missing);
        
        // 設置表格邊框
        table.Borders.Enable = 1;
        table.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
        table.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
        
        // 設置表頭
        table.Cell(1, 1).Range.Text = "姓名";
        table.Cell(1, 2).Range.Text = "部門";
        table.Cell(1, 3).Range.Text = "職位";
        
        // 設置表頭樣式
        for (int col = 1; col <= 3; col++)
        {
            table.Cell(1, col).Range.Font.Bold = 1;
            table.Cell(1, col).Range.Font.Size = 12;
            table.Cell(1, col).Range.Font.Color = Word.WdColor.wdColorWhite;
            table.Cell(1, col).Shading.BackgroundPatternColor = Word.WdColor.wdColorBlue;
            table.Cell(1, col).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
        }
        
        // 填充數(shù)據(jù)
        string[,] data = {
            {"張三", "技術部", "工程師"},
            {"李四", "市場部", "經(jīng)理"},
            {"王五", "財務部", "會計"},
            {"趙六", "人事部", "主管"}
        };
        
        for (int row = 0; row < 4; row++)
        {
            for (int col = 0; col < 3; col++)
            {
                table.Cell(row + 2, col + 1).Range.Text = data[row, col];
                table.Cell(row + 2, col + 1).Range.Font.Size = 11;
                table.Cell(row + 2, col + 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            }
        }
        
        // 自動調整表格
        table.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent);
        
        // 保存文檔
        object fileName = filePath;
        doc.SaveAs2(ref fileName);
        
        Console.WriteLine("帶表格的Word文檔創(chuàng)建成功: " + filePath);
    }
    catch (Exception ex)
    {
        Console.WriteLine("插入表格時出錯: " + ex.Message);
        throw;
    }
    finally
    {
        if (doc != null)
        {
            doc.Close();
            Marshal.ReleaseComObject(doc);
        }
        if (wordApp != null)
        {
            wordApp.Quit();
            Marshal.ReleaseComObject(wordApp);
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

4. 刪除Word中的表格

/// <summary>
/// 刪除Word文檔中的指定表格
/// </summary>
public static void DeleteTableInWord(string filePath, int tableIndex)
{
    Word.Application wordApp = null;
    Word.Document doc = null;
    
    try
    {
        wordApp = new Word.Application();
        wordApp.Visible = false;
        
        object fileName = filePath;
        object missing = System.Reflection.Missing.Value;
        
        doc = wordApp.Documents.Open(ref fileName, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing);
        
        // 檢查表格是否存在
        if (doc.Tables.Count >= tableIndex)
        {
            doc.Tables[tableIndex].Delete();
            Console.WriteLine("已刪除第 {0} 個表格", tableIndex);
            
            // 保存修改
            doc.Save();
        }
        else
        {
            Console.WriteLine("表格索引超出范圍,文檔中共有 {0} 個表格", doc.Tables.Count);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("刪除表格時出錯: " + ex.Message);
        throw;
    }
    finally
    {
        if (doc != null)
        {
            doc.Close();
            Marshal.ReleaseComObject(doc);
        }
        if (wordApp != null)
        {
            wordApp.Quit();
            Marshal.ReleaseComObject(wordApp);
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

5. 修改Word文檔

/// <summary>
/// 修改Word文檔內容
/// </summary>
public static void ModifyWordDocument(string filePath)
{
    Word.Application wordApp = null;
    Word.Document doc = null;
    
    try
    {
        wordApp = new Word.Application();
        wordApp.Visible = false;
        
        object fileName = filePath;
        object missing = System.Reflection.Missing.Value;
        
        doc = wordApp.Documents.Open(ref fileName, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing);
        
        // 在文檔末尾添加新內容
        Word.Paragraph newPara = doc.Paragraphs.Add(ref missing);
        newPara.Range.Text = "這是新添加的內容";
        newPara.Range.Font.Size = 12;
        newPara.Range.Font.Color = Word.WdColor.wdColorGreen;
        newPara.Range.Font.Bold = 1;
        
        // 查找并替換文本
        Word.Find findObject = wordApp.Selection.Find;
        findObject.Text = "舊文本";
        findObject.Replacement.Text = "新文本";
        
        object replaceAll = Word.WdReplace.wdReplaceAll;
        findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing, ref missing,
            ref replaceAll, ref missing, ref missing, ref missing, ref missing);
        
        // 保存修改
        doc.Save();
        
        Console.WriteLine("Word文檔修改成功");
    }
    catch (Exception ex)
    {
        Console.WriteLine("修改Word文檔時出錯: " + ex.Message);
        throw;
    }
    finally
    {
        if (doc != null)
        {
            doc.Close();
            Marshal.ReleaseComObject(doc);
        }
        if (wordApp != null)
        {
            wordApp.Quit();
            Marshal.ReleaseComObject(wordApp);
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

Excel文檔操作

1. 創(chuàng)建Excel文檔

public class ExcelDocumentHelper
{
    /// <summary>
    /// 創(chuàng)建Excel文檔
    /// </summary>
    public static void CreateExcelDocument(string filePath)
    {
        Excel.Application excelApp = null;
        Excel.Workbook workbook = null;
        Excel.Worksheet worksheet = null;
        
        try
        {
            excelApp = new Excel.Application();
            excelApp.Visible = false;
            excelApp.DisplayAlerts = false;
            
            // 創(chuàng)建新工作簿
            workbook = excelApp.Workbooks.Add(Type.Missing);
            worksheet = (Excel.Worksheet)workbook.Worksheets[1];
            worksheet.Name = "銷售數(shù)據(jù)";
            
            // 設置標題行
            worksheet.Cells[1, 1] = "產(chǎn)品名稱";
            worksheet.Cells[1, 2] = "銷售數(shù)量";
            worksheet.Cells[1, 3] = "單價";
            worksheet.Cells[1, 4] = "總金額";
            
            // 設置標題行樣式
            Excel.Range titleRange = worksheet.Range["A1", "D1"];
            titleRange.Font.Bold = true;
            titleRange.Font.Size = 12;
            titleRange.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
            titleRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue);
            titleRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
            
            // 填充數(shù)據(jù)
            string[] products = { "筆記本電腦", "鼠標", "鍵盤", "顯示器", "耳機" };
            int[] quantities = { 50, 200, 150, 80, 120 };
            double[] prices = { 5000.00, 50.00, 150.00, 1500.00, 200.00 };
            
            for (int i = 0; i < products.Length; i++)
            {
                int row = i + 2;
                worksheet.Cells[row, 1] = products[i];
                worksheet.Cells[row, 2] = quantities[i];
                worksheet.Cells[row, 3] = prices[i];
                
                // 設置公式計算總金額
                worksheet.Cells[row, 4].Formula = string.Format("=B{0}*C{1}", row, row);
                
                // 設置數(shù)字格式
                worksheet.Cells[row, 3].NumberFormat = "¥#,##0.00";
                worksheet.Cells[row, 4].NumberFormat = "¥#,##0.00";
            }
            
            // 添加合計行
            int totalRow = products.Length + 2;
            worksheet.Cells[totalRow, 1] = "合計";
            worksheet.Cells[totalRow, 1].Font.Bold = true;
            worksheet.Cells[totalRow, 4].Formula = string.Format("=SUM(D2:D{0})", totalRow - 1);
            worksheet.Cells[totalRow, 4].Font.Bold = true;
            worksheet.Cells[totalRow, 4].NumberFormat = "¥#,##0.00";
            worksheet.Cells[totalRow, 4].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightYellow);
            
            // 設置列寬自適應
            worksheet.Columns.AutoFit();
            
            // 添加邊框
            Excel.Range dataRange = worksheet.Range["A1", string.Format("D{0}", totalRow)];
            dataRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
            dataRange.Borders.Weight = Excel.XlBorderWeight.xlThin;
            
            // 保存文件
            workbook.SaveAs(filePath, Excel.XlFileFormat.xlWorkbookDefault,
                Type.Missing, Type.Missing, false, false,
                Excel.XlSaveAsAccessMode.xlNoChange,
                Excel.XlSaveConflictResolution.xlLocalSessionChanges,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            
            Console.WriteLine("Excel文檔創(chuàng)建成功: " + filePath);
        }
        catch (Exception ex)
        {
            Console.WriteLine("創(chuàng)建Excel文檔時出錯: " + ex.Message);
            throw;
        }
        finally
        {
            if (worksheet != null) Marshal.ReleaseComObject(worksheet);
            if (workbook != null)
            {
                workbook.Close();
                Marshal.ReleaseComObject(workbook);
            }
            if (excelApp != null)
            {
                excelApp.Quit();
                Marshal.ReleaseComObject(excelApp);
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}

2. 讀取Excel文檔

/// <summary>
/// 讀取Excel文檔
/// </summary>
public static void ReadExcelDocument(string filePath)
{
    Excel.Application excelApp = null;
    Excel.Workbook workbook = null;
    Excel.Worksheet worksheet = null;
    
    try
    {
        excelApp = new Excel.Application();
        excelApp.Visible = false;
        excelApp.DisplayAlerts = false;
        
        // 打開工作簿
        workbook = excelApp.Workbooks.Open(filePath,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing);
        
        worksheet = (Excel.Worksheet)workbook.Worksheets[1];
        
        // 獲取使用的范圍
        Excel.Range usedRange = worksheet.UsedRange;
        int rowCount = usedRange.Rows.Count;
        int colCount = usedRange.Columns.Count;
        
        Console.WriteLine("工作表名稱: " + worksheet.Name);
        Console.WriteLine("行數(shù): {0}, 列數(shù): {1}", rowCount, colCount);
        Console.WriteLine("\n數(shù)據(jù)內容:");
        
        // 讀取所有數(shù)據(jù)
        for (int row = 1; row <= rowCount; row++)
        {
            for (int col = 1; col <= colCount; col++)
            {
                Excel.Range cell = (Excel.Range)worksheet.Cells[row, col];
                object value = cell.Value2;
                
                if (value != null)
                {
                    Console.Write(value.ToString() + "\t");
                }
                else
                {
                    Console.Write("NULL\t");
                }
            }
            Console.WriteLine();
        }
        
        // 讀取特定單元格
        Excel.Range specificCell = (Excel.Range)worksheet.Cells[2, 1];
        Console.WriteLine("\n單元格A2的值: " + specificCell.Value2);
        Console.WriteLine("單元格A2的字體大小: " + specificCell.Font.Size);
        Console.WriteLine("單元格A2的字體顏色: " + specificCell.Font.Color);
    }
    catch (Exception ex)
    {
        Console.WriteLine("讀取Excel文檔時出錯: " + ex.Message);
        throw;
    }
    finally
    {
        if (worksheet != null) Marshal.ReleaseComObject(worksheet);
        if (workbook != null)
        {
            workbook.Close();
            Marshal.ReleaseComObject(workbook);
        }
        if (excelApp != null)
        {
            excelApp.Quit();
            Marshal.ReleaseComObject(excelApp);
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

3. 修改Excel文檔

/// <summary>
/// 修改Excel文檔
/// </summary>
public static void ModifyExcelDocument(string filePath)
{
    Excel.Application excelApp = null;
    Excel.Workbook workbook = null;
    Excel.Worksheet worksheet = null;
    
    try
    {
        excelApp = new Excel.Application();
        excelApp.Visible = false;
        excelApp.DisplayAlerts = false;
        
        workbook = excelApp.Workbooks.Open(filePath,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing);
        
        worksheet = (Excel.Worksheet)workbook.Worksheets[1];
        
        // 修改特定單元格
        worksheet.Cells[2, 2] = 250; // 修改銷售數(shù)量
        
        // 添加新行
        int lastRow = worksheet.UsedRange.Rows.Count + 1;
        worksheet.Cells[lastRow, 1] = "新產(chǎn)品";
        worksheet.Cells[lastRow, 2] = 100;
        worksheet.Cells[lastRow, 3] = 300.00;
        worksheet.Cells[lastRow, 4].Formula = string.Format("=B{0}*C{1}", lastRow, lastRow);
        
        // 設置新行樣式
        Excel.Range newRow = worksheet.Range[string.Format("A{0}", lastRow), string.Format("D{0}", lastRow)];
        newRow.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
        newRow.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
        
        // 保存修改
        workbook.Save();
        
        Console.WriteLine("Excel文檔修改成功");
    }
    catch (Exception ex)
    {
        Console.WriteLine("修改Excel文檔時出錯: " + ex.Message);
        throw;
    }
    finally
    {
        if (worksheet != null) Marshal.ReleaseComObject(worksheet);
        if (workbook != null)
        {
            workbook.Close();
            Marshal.ReleaseComObject(workbook);
        }
        if (excelApp != null)
        {
            excelApp.Quit();
            Marshal.ReleaseComObject(excelApp);
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

4. Excel添加圖表

/// <summary>
/// 在Excel中添加圖表
/// </summary>
public static void AddChartToExcel(string filePath)
{
    Excel.Application excelApp = null;
    Excel.Workbook workbook = null;
    Excel.Worksheet worksheet = null;
    
    try
    {
        excelApp = new Excel.Application();
        excelApp.Visible = false;
        excelApp.DisplayAlerts = false;
        
        workbook = excelApp.Workbooks.Open(filePath,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing);
        
        worksheet = (Excel.Worksheet)workbook.Worksheets[1];
        
        // 創(chuàng)建圖表
        Excel.ChartObjects chartObjs = (Excel.ChartObjects)worksheet.ChartObjects(Type.Missing);
        Excel.ChartObject chartObj = chartObjs.Add(300, 50, 400, 300);
        Excel.Chart chart = chartObj.Chart;
        
        // 設置數(shù)據(jù)源(假設數(shù)據(jù)在A1:D6)
        Excel.Range dataRange = worksheet.Range["A1", "D6"];
        chart.SetSourceData(dataRange, Type.Missing);
        
        // 設置圖表類型為柱狀圖
        chart.ChartType = Excel.XlChartType.xlColumnClustered;
        
        // 設置圖表標題
        chart.HasTitle = true;
        chart.ChartTitle.Text = "產(chǎn)品銷售統(tǒng)計";
        chart.ChartTitle.Font.Size = 14;
        chart.ChartTitle.Font.Bold = true;
        
        workbook.Save();
        
        Console.WriteLine("圖表添加成功");
    }
    catch (Exception ex)
    {
        Console.WriteLine("添加圖表時出錯: " + ex.Message);
        throw;
    }
    finally
    {
        if (worksheet != null) Marshal.ReleaseComObject(worksheet);
        if (workbook != null)
        {
            workbook.Close();
            Marshal.ReleaseComObject(workbook);
        }
        if (excelApp != null)
        {
            excelApp.Quit();
            Marshal.ReleaseComObject(excelApp);
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

PowerPoint文檔操作

1. 創(chuàng)建PowerPoint文檔

public class PowerPointDocumentHelper
{
    /// <summary>
    /// 創(chuàng)建PowerPoint文檔
    /// </summary>
    public static void CreatePowerPointDocument(string filePath)
    {
        PowerPoint.Application pptApp = null;
        PowerPoint.Presentation presentation = null;
        
        try
        {
            pptApp = new PowerPoint.Application();
            
            // 創(chuàng)建新演示文稿
            presentation = pptApp.Presentations.Add(MsoTriState.msoTrue);
            
            // 添加標題幻燈片
            PowerPoint.Slide slide1 = presentation.Slides.Add(1, PowerPoint.PpSlideLayout.ppLayoutTitle);
            PowerPoint.TextRange titleRange = slide1.Shapes[1].TextFrame.TextRange;
            titleRange.Text = "公司年度報告";
            titleRange.Font.Size = 44;
            titleRange.Font.Bold = MsoTriState.msoTrue;
            titleRange.Font.Color.RGB = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.DarkBlue);
            titleRange.Font.Name = "微軟雅黑";
            
            PowerPoint.TextRange subtitleRange = slide1.Shapes[2].TextFrame.TextRange;
            subtitleRange.Text = "2024年度總結\n演示文稿";
            subtitleRange.Font.Size = 24;
            subtitleRange.Font.Color.RGB = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Gray);
            
            // 添加內容幻燈片
            PowerPoint.Slide slide2 = presentation.Slides.Add(2, PowerPoint.PpSlideLayout.ppLayoutText);
            PowerPoint.TextRange slide2Title = slide2.Shapes[1].TextFrame.TextRange;
            slide2Title.Text = "主要內容";
            slide2Title.Font.Size = 32;
            slide2Title.Font.Bold = MsoTriState.msoTrue;
            slide2Title.Font.Color.RGB = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.DarkBlue);
            
            PowerPoint.TextRange slide2Content = slide2.Shapes[2].TextFrame.TextRange;
            slide2Content.Text = "? 市場分析\n? 財務報告\n? 團隊建設\n? 未來規(guī)劃";
            slide2Content.Font.Size = 20;
            slide2Content.ParagraphFormat.Bullet.Type = PowerPoint.PpBulletType.ppBulletUnnumbered;
            
            // 添加帶圖片的幻燈片
            PowerPoint.Slide slide3 = presentation.Slides.Add(3, PowerPoint.PpSlideLayout.ppLayoutTitleOnly);
            PowerPoint.TextRange slide3Title = slide3.Shapes[1].TextFrame.TextRange;
            slide3Title.Text = "數(shù)據(jù)展示";
            slide3Title.Font.Size = 32;
            slide3Title.Font.Bold = MsoTriState.msoTrue;
            
            // 添加文本框
            PowerPoint.Shape textBox = slide3.Shapes.AddTextbox(
                MsoTextOrientation.msoTextOrientationHorizontal,
                100, 150, 600, 300);
            textBox.TextFrame.TextRange.Text = "這里可以展示重要數(shù)據(jù)和圖表";
            textBox.TextFrame.TextRange.Font.Size = 24;
            textBox.TextFrame.TextRange.Font.Color.RGB = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
            textBox.Fill.ForeColor.RGB = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightYellow);
            textBox.Line.Visible = MsoTriState.msoTrue;
            
            // 保存演示文稿
            presentation.SaveAs(filePath, PowerPoint.PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoTrue);
            
            Console.WriteLine("PowerPoint文檔創(chuàng)建成功: " + filePath);
        }
        catch (Exception ex)
        {
            Console.WriteLine("創(chuàng)建PowerPoint文檔時出錯: " + ex.Message);
            throw;
        }
        finally
        {
            if (presentation != null)
            {
                presentation.Close();
                Marshal.ReleaseComObject(presentation);
            }
            if (pptApp != null)
            {
                pptApp.Quit();
                Marshal.ReleaseComObject(pptApp);
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}

2. 讀取PowerPoint文檔

/// <summary>
/// 讀取PowerPoint文檔
/// </summary>
public static void ReadPowerPointDocument(string filePath)
{
    PowerPoint.Application pptApp = null;
    PowerPoint.Presentation presentation = null;
    
    try
    {
        pptApp = new PowerPoint.Application();
        
        // 打開演示文稿
        presentation = pptApp.Presentations.Open(filePath,
            MsoTriState.msoTrue, // ReadOnly
            MsoTriState.msoTrue, // Untitled
            MsoTriState.msoFalse); // WithWindow
        
        Console.WriteLine("演示文稿名稱: " + presentation.Name);
        Console.WriteLine("幻燈片數(shù)量: " + presentation.Slides.Count);
        Console.WriteLine("\n幻燈片內容:");
        
        // 遍歷所有幻燈片
        foreach (PowerPoint.Slide slide in presentation.Slides)
        {
            Console.WriteLine("\n--- 幻燈片 " + slide.SlideIndex + " ---");
            
            // 遍歷幻燈片中的所有形狀
            foreach (PowerPoint.Shape shape in slide.Shapes)
            {
                if (shape.HasTextFrame == MsoTriState.msoTrue)
                {
                    if (shape.TextFrame.HasText == MsoTriState.msoTrue)
                    {
                        Console.WriteLine("文本內容: " + shape.TextFrame.TextRange.Text);
                        Console.WriteLine("字體大小: " + shape.TextFrame.TextRange.Font.Size);
                        Console.WriteLine("字體名稱: " + shape.TextFrame.TextRange.Font.Name);
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("讀取PowerPoint文檔時出錯: " + ex.Message);
        throw;
    }
    finally
    {
        if (presentation != null)
        {
            presentation.Close();
            Marshal.ReleaseComObject(presentation);
        }
        if (pptApp != null)
        {
            pptApp.Quit();
            Marshal.ReleaseComObject(pptApp);
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

3. 修改PowerPoint文檔

/// <summary>
/// 修改PowerPoint文檔
/// </summary>
public static void ModifyPowerPointDocument(string filePath)
{
    PowerPoint.Application pptApp = null;
    PowerPoint.Presentation presentation = null;
    
    try
    {
        pptApp = new PowerPoint.Application();
        
        presentation = pptApp.Presentations.Open(filePath,
            MsoTriState.msoFalse, // ReadOnly = false
            MsoTriState.msoTrue,
            MsoTriState.msoFalse);
        
        // 修改第一張幻燈片的標題
        if (presentation.Slides.Count > 0)
        {
            PowerPoint.Slide slide1 = presentation.Slides[1];
            if (slide1.Shapes.Count > 0)
            {
                slide1.Shapes[1].TextFrame.TextRange.Text = "修改后的標題";
                slide1.Shapes[1].TextFrame.TextRange.Font.Color.RGB = 
                    System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
            }
        }
        
        // 添加新幻燈片
        PowerPoint.Slide newSlide = presentation.Slides.Add(
            presentation.Slides.Count + 1,
            PowerPoint.PpSlideLayout.ppLayoutText);
        
        newSlide.Shapes[1].TextFrame.TextRange.Text = "新添加的幻燈片";
        newSlide.Shapes[1].TextFrame.TextRange.Font.Size = 32;
        newSlide.Shapes[2].TextFrame.TextRange.Text = "這是新添加的內容";
        newSlide.Shapes[2].TextFrame.TextRange.Font.Size = 20;
        
        // 保存修改
        presentation.Save();
        
        Console.WriteLine("PowerPoint文檔修改成功");
    }
    catch (Exception ex)
    {
        Console.WriteLine("修改PowerPoint文檔時出錯: " + ex.Message);
        throw;
    }
    finally
    {
        if (presentation != null)
        {
            presentation.Close();
            Marshal.ReleaseComObject(presentation);
        }
        if (pptApp != null)
        {
            pptApp.Quit();
            Marshal.ReleaseComObject(pptApp);
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

轉換為PDF

1. Word轉PDF

public class PDFConverter
{
    /// <summary>
    /// 將Word文檔轉換為PDF
    /// </summary>
    public static void ConvertWordToPDF(string wordFilePath, string pdfFilePath)
    {
        Word.Application wordApp = null;
        Word.Document doc = null;
        
        try
        {
            wordApp = new Word.Application();
            wordApp.Visible = false;
            
            object fileName = wordFilePath;
            object missing = System.Reflection.Missing.Value;
            
            doc = wordApp.Documents.Open(ref fileName, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing);
            
            // 導出為PDF
            doc.ExportAsFixedFormat(pdfFilePath,
                Word.WdExportFormat.wdExportFormatPDF,
                false, // OpenAfterExport
                Word.WdExportOptimizeFor.wdExportOptimizeForPrint,
                Word.WdExportRange.wdExportAllDocument,
                0, // From
                0, // To
                Word.WdExportItem.wdExportDocumentContent,
                true, // IncludeDocProps
                true, // KeepIRM
                Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks,
                true, // DocStructureTags
                true, // BitmapMissingFonts
                false); // UseISO19005_1
            
            Console.WriteLine("Word轉PDF成功: " + pdfFilePath);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Word轉PDF時出錯: " + ex.Message);
            throw;
        }
        finally
        {
            if (doc != null)
            {
                doc.Close();
                Marshal.ReleaseComObject(doc);
            }
            if (wordApp != null)
            {
                wordApp.Quit();
                Marshal.ReleaseComObject(wordApp);
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}

2. Excel轉PDF

/// <summary>
/// 將Excel文檔轉換為PDF
/// </summary>
public static void ConvertExcelToPDF(string excelFilePath, string pdfFilePath)
{
    Excel.Application excelApp = null;
    Excel.Workbook workbook = null;
    
    try
    {
        excelApp = new Excel.Application();
        excelApp.Visible = false;
        excelApp.DisplayAlerts = false;
        
        workbook = excelApp.Workbooks.Open(excelFilePath,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing);
        
        // 導出為PDF
        workbook.ExportAsFixedFormat(
            Excel.XlFixedFormatType.xlTypePDF,
            pdfFilePath,
            Excel.XlFixedFormatQuality.xlQualityStandard,
            true, // IncludeDocProperties
            false, // IgnorePrintAreas
            Type.Missing,
            Type.Missing,
            false, // OpenAfterPublish
            Type.Missing);
        
        Console.WriteLine("Excel轉PDF成功: " + pdfFilePath);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Excel轉PDF時出錯: " + ex.Message);
        throw;
    }
    finally
    {
        if (workbook != null)
        {
            workbook.Close();
            Marshal.ReleaseComObject(workbook);
        }
        if (excelApp != null)
        {
            excelApp.Quit();
            Marshal.ReleaseComObject(excelApp);
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

3. PowerPoint轉PDF

/// <summary>
/// 將PowerPoint文檔轉換為PDF
/// </summary>
public static void ConvertPowerPointToPDF(string pptFilePath, string pdfFilePath)
{
    PowerPoint.Application pptApp = null;
    PowerPoint.Presentation presentation = null;
    
    try
    {
        pptApp = new PowerPoint.Application();
        
        presentation = pptApp.Presentations.Open(pptFilePath,
            MsoTriState.msoTrue,
            MsoTriState.msoTrue,
            MsoTriState.msoFalse);
        
        // 導出為PDF
        presentation.ExportAsFixedFormat(
            pdfFilePath,
            PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF,
            PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentPrint,
            MsoTriState.msoFalse, // FrameSlides
            PowerPoint.PpPrintHandoutOrder.ppPrintHandoutVerticalFirst,
            PowerPoint.PpPrintOutputType.ppPrintOutputSlides,
            MsoTriState.msoFalse, // PrintHiddenSlides
            null,
            PowerPoint.PpPrintRangeType.ppPrintAll,
            string.Empty,
            true, // IncludeDocProperties
            true, // KeepIRMSettings
            true, // DocStructureTags
            true, // BitmapMissingFonts
            false); // UseISO19005_1
        
        Console.WriteLine("PowerPoint轉PDF成功: " + pdfFilePath);
    }
    catch (Exception ex)
    {
        Console.WriteLine("PowerPoint轉PDF時出錯: " + ex.Message);
        throw;
    }
    finally
    {
        if (presentation != null)
        {
            presentation.Close();
            Marshal.ReleaseComObject(presentation);
        }
        if (pptApp != null)
        {
            pptApp.Quit();
            Marshal.ReleaseComObject(pptApp);
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

完整示例程序

using System;
using System.IO;
using System.Runtime.InteropServices;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;

namespace OfficeDocumentDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string outputDir = @"C:\OfficeDocuments\";
                
                // 創(chuàng)建輸出目錄
                if (!Directory.Exists(outputDir))
                {
                    Directory.CreateDirectory(outputDir);
                }
                
                Console.WriteLine("開始Office文檔操作演示...\n");
                
                // Word操作
                Console.WriteLine("=== Word文檔操作 ===");
                string wordFile = Path.Combine(outputDir, "示例文檔.docx");
                string wordWithTable = Path.Combine(outputDir, "帶表格文檔.docx");
                
                WordDocumentHelper.CreateWordDocument(wordFile);
                WordDocumentHelper.InsertTableInWord(wordWithTable);
                WordDocumentHelper.ReadWordDocument(wordFile);
                
                // Excel操作
                Console.WriteLine("\n=== Excel文檔操作 ===");
                string excelFile = Path.Combine(outputDir, "銷售數(shù)據(jù).xlsx");
                
                ExcelDocumentHelper.CreateExcelDocument(excelFile);
                ExcelDocumentHelper.ReadExcelDocument(excelFile);
                ExcelDocumentHelper.ModifyExcelDocument(excelFile);
                
                // PowerPoint操作
                Console.WriteLine("\n=== PowerPoint文檔操作 ===");
                string pptFile = Path.Combine(outputDir, "年度報告.pptx");
                
                PowerPointDocumentHelper.CreatePowerPointDocument(pptFile);
                PowerPointDocumentHelper.ReadPowerPointDocument(pptFile);
                
                // PDF轉換
                Console.WriteLine("\n=== 轉換為PDF ===");
                PDFConverter.ConvertWordToPDF(wordFile, Path.Combine(outputDir, "示例文檔.pdf"));
                PDFConverter.ConvertExcelToPDF(excelFile, Path.Combine(outputDir, "銷售數(shù)據(jù).pdf"));
                PDFConverter.ConvertPowerPointToPDF(pptFile, Path.Combine(outputDir, "年度報告.pdf"));
                
                Console.WriteLine("\n所有操作完成!");
                Console.WriteLine("文件保存在: " + outputDir);
            }
            catch (Exception ex)
            {
                Console.WriteLine("程序執(zhí)行出錯: " + ex.Message);
                Console.WriteLine("堆棧跟蹤: " + ex.StackTrace);
            }
            
            Console.WriteLine("\n按任意鍵退出...");
            Console.ReadKey();
        }
    }
}

注意事項

1. COM對象釋放

必須正確釋放COM對象,避免內存泄漏:

// 正確的釋放順序
if (worksheet != null) Marshal.ReleaseComObject(worksheet);
if (workbook != null) 
{
    workbook.Close();
    Marshal.ReleaseComObject(workbook);
}
if (excelApp != null) 
{
    excelApp.Quit();
    Marshal.ReleaseComObject(excelApp);
}
GC.Collect();
GC.WaitForPendingFinalizers();

2. Office版本兼容性

  • 代碼基于Office 2010(14.0版本)
  • 不同Office版本可能有API差異
  • 建議檢查目標機器的Office版本

3. 錯誤處理

try
{
    // Office操作代碼
}
catch (COMException comEx)
{
    Console.WriteLine("COM異常: " + comEx.Message);
}
catch (Exception ex)
{
    Console.WriteLine("一般異常: " + ex.Message);
}
finally
{
    // 清理資源
}

4. 性能優(yōu)化建議

  • 批量操作時關閉屏幕更新:excelApp.ScreenUpdating = false;
  • 關閉自動計算:excelApp.Calculation = Excel.XlCalculation.xlCalculationManual;
  • 完成后記得恢復設置

5. 常見問題

問題1:找不到Office庫引用

解決:確保安裝了Office 2010在COM引用中添加Microsoft Office 14.0 Object Library

問題2:權限錯誤

解決:以管理員身份運行程序檢查文件路徑的寫入權限

問題3:進程未正確關閉

  • 解決:使用Task Manager檢查是否有殘留的Office進程
  • 確保finally塊中正確調用Quit()和ReleaseComObject()

6. 部署注意事項

  • 目標機器必須安裝Microsoft Office
  • 需要安裝.NET Framework 4.0或更高版本
  • 某些功能需要Office激活

7. 顏色設置說明

// Word中的顏色
range.Font.Color = Word.WdColor.wdColorRed;

// Excel中的顏色(使用RGB)
cell.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

// PowerPoint中的顏色
shape.TextFrame.TextRange.Font.Color.RGB = 
    System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

總結

本教程涵蓋了C#中操作Office文檔的核心功能:

? Word操作:創(chuàng)建、讀取、修改、表格操作
? Excel操作:數(shù)據(jù)處理、格式設置、公式計算
? PowerPoint操作:幻燈片創(chuàng)建、內容編輯
? PDF轉換:三種文檔格式轉PDF
? 樣式設置:字體、顏色、大小等

代碼可直接在Visual Studio 2010和.NET Framework 4.0環(huán)境下使用。

以上就是C#中操作Office文檔的完整教程的詳細內容,更多關于C#操作Office文檔的資料請關注腳本之家其它相關文章!

相關文章

最新評論

县级市| 洛阳市| 托克托县| 邯郸市| 商城县| 兴国县| 安丘市| 浠水县| 大安市| 通化县| 多伦县| 禄劝| 托克逊县| 平顺县| 哈巴河县| 育儿| 湘潭市| 宁晋县| 赤城县| 常德市| 黔东| 焦作市| 眉山市| 邳州市| 西平县| 博客| 紫阳县| 土默特左旗| 昌邑市| 新田县| 西安市| 宣恩县| 增城市| 天峨县| 龙胜| 文登市| 蓝山县| 凤凰县| 仁布县| 三原县| 策勒县|