开发者

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

目录
  • 环境准备
    • 1. 安装Microsoft Office Interop组件
    • 2. 必要的using语句
  • Word文档操作
    • 1. 创建Word文档
    • 2. 读取Word文档
    • 3. 在Word中插入表格
    • 4. 删除Word中的表格
    • 5. 修改Word文档
  • Excel文档操作
    • 1. 创建Excel文档
    • 2. 读取Excel文档
    • 3. 修改Excel文档
    • 4. Excel添加图表
  • PowerPoint文档操作
    • 1. 创建PowerPoint文档
    • 2. 读取PowerPoint文档
    • 3. 修改PowerPoint文档
  • 转换为PDF
    • 1. Word转PDF
    • 2. Excel转PDF
    • 3. PowerPoint转PDF
  • 完整示例程序
    • 注意事项
      • 1. COM对象释放
      • 2. Office版本兼容性
      • 3. 错误处理
      • 4. 性能优化建议
      • 5. 常见问题
      • 6. 部署注意事项
      • 7. 颜色设置说明
    • 总结

      环境准备

      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. 创建Word文档

      public class WordDocumentHelper
      {
          /// <summary>
          /// 创建新的Word文档
          /// </summary>
          public static void CreateWordDocument(string filePath)
          {
              Word.Application wordApp = null;
              Word.Document doc = null;
              
              try
              {
                  // 创建Word应用程序实例
                  wordApp = new Word.Application();
                  wordApp.Visible = false; // 不显示Word窗口
                  
                  // 创建新文档
                  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文档创建成功: " + filePath);
              }
              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();
              }
          }
      }
      

      2. 读取Word文档

      public class WordDocumentHelper
      {
          /// <summary>
          /// 创建新的Word文档
          /// </summary>
          public static void CreateWordDocument(string filePath)
          {
              Word.Application wordApp = null;
              Word.Document doc = null;
              
              try
              {
                  // 创建Word应用程序实例
                  wordApp = new Word.Application();
                  wordApp.Visible = false; // 不显示Word窗口
                  
                  // 创建新文档
                  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文档创建成功: " + filePath);
              }
              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();
              }
          }
      }
      

      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;
              }
              
              // 填充数据
              string[,] data = {
                  {"张三", "技术部", "工程师"},
                  {"李四", "市场部", "经理"},
                  {"王五", "财务部", "会计"},
                  {"赵六", "人事部", "主管"}
              };
              
              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文档创建成功: " + 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);
      js        }
          }
          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. 创建Excel文档

      public class ExcelDocumentHelper
      {
          /// <summary>
          /// 创建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;
                  
                  // 创建新工作簿
                  workbook = excelApp.Workbooks.Add(Type.Missing);
                  worksheet = (Excel.Worksheet)workbook.Worksheets[1];
                  worksheet.Name = "销售数据";
                  
                  // 设置标题行
                  worksheet.Cells[1, 1] = "产品名称";
                  worksheet.Cells[1, 2] = "销售数量";
                  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;
                  
                  // 填充数据
                  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);
                      
                      // 设置数字格式
                      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文档创建成功: " + filePath);
              }
              catch (Exception ex)
              {
                  Console.WriteLine("创建Excel文档时出错: " + ex.Message);
                  throw;
              }
              finally
              {
                  if (worksheet != null) Marshal.ReleaseComObject(worksheet);
                  if (workbook != null)
                  {
          www.devze.com            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("行数: {0}, 列数: {1}", rowCount, colCount);
              Console.WriteLine("\n数据内容:");
              
              // 读取所有数据
              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; // 修改销售数量
              
              // 添加新行
              int lastRow = worksheet.UsedRange.Rows.Count + 1;
              worksheet.Cells[lastRow, 1] = "新产品";
              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];
              
              // 创建图表
              Excel.ChartObjects chartObjs = (Excel.ChartObjects)worksheet.ChartObjects(Type.Missing);
              Excel.ChartObject chartObj = chartObjs.Add(300, 50, 400, 300);
              Excel.Chart chart = chartObj.Chart;
              
              // 设置数据源(假设数据在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 = "产品销售统计";
              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(http://www.devze.com);
              GC.WaitForPendingFinalizers();
          }
      }
      

      PowerPoint文档操作

      1. 创建PowerPoint文档

      public class PowerPointDocumentHelper
      {
          /// <summary>
          /// 创建PowerPoint文档
          /// </summary>
          public static void CreatePowerPointDocument(string filePath)
          {
              PowerPoint.Application pptApp = null;
              PowerPoint.Presentation presentation = null;
              
              try
              {
                  pptApp = new PowerPoint.Application();
                  
                  // 创建新演示文稿
                  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• 未来规划";
                  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 = "数据展示";
                  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 = "这里可以展示重要数据和图表";
                  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文档创建成功: " + filePath);
              }
              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();
              }
          }
      }
      

      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("幻灯片数量: " + 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\";
                      
                      // 创建输出目录
                      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, "销售数据.xlsx");
                      
                      ExcelDocumentHelper.CreateExcelDocument(excelFile);
                      ExcelDocumentHelper.ReadExcelDocument(excelFile);
                      ExcelDocumentHelper.ModifyExcelDocument(excelFile);
                      
                      // PowerPoint操作
                      Console.WriteLine("\n=== PowerPoint文档操作 ===");
                      string pptFile = Path.Combine(outputDir, "年度报告.pptx");
                      
                      PowerPointDocumentHelper.CreatePowerPointDocument(pptFile);
                      PowerPointDocumentHelhttp://www.devze.comper.ReadPowerPointDocument(pptFile);
                      
                      // PDF转换
                      Console.WriteLine("\n=== 转换为PDF ===");
                      PDFConverter.ConvertWordToPDF(wordFile, Path.Combine(outputDir, "示例文档.pdf"));
                      PDFConverter.ConvertExcelToPDF(excelFile, Path.Combine(outputDir, "销售数据.pdf"));
                      PDFConverter.ConvertPowerPointToPDF(pptFile, Path.Combine(outputDir, "年度报告.pdf"));
                      
                      Console.WriteLine("\n所有操作完成!");
                      Console.WriteLine("文件保存在: " + outputDir);
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine("程序执行出错: " + ex.Message);
                      Console.WriteLine("堆栈跟踪: " + ex.StackTrace);
                  }
                  
                  Console.WriteLine("\n按任意键退出...");
                  Console.ReadKey();
              }
          }
      }
      

      注意事项

      1.php 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. 性能优化建议

      • 批量操作时关闭屏幕更新: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操作:创建、读取、修改、表格操作

      Excel操作:数据处理、格式设置、公式计算

      PowerPoint操作:幻灯片创建、内容编辑

      PDF转换:三种文档格式转PDF

      样式设置:字体、颜色、大小等

      代码可直接在Visual Studio 2010和.NET Framework 4.0环境下使用。

      以上就是C#中操作Office文档的完整教程的详细内容,更多关于C#操作Office文档的资料请关注编程客栈(www.devze.com)其它相关文章!

      0

      上一篇:

      下一篇:

      精彩评论

      暂无评论...
      验证码 换一张
      取 消

      最新开发

      开发排行榜