先看运行结果 → 运行结果
开发环境- Microsoft Visual Studio Community 2019
- Microsoft .NET Framework 4.8.04084
- Microsoft Excel 2016
- C#
新建「C#控制台应用程序」项目,参照以下内容
快速入门:使用 Visual Studio 创建第一个 C# 控制台应用
添加「Microsoft Excel 16.0 Object Library」COM引用,只找到一篇简单易懂的日语文章
在 .NET 5 项目中添加 COM 引用
using System.IO;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelEdit
{
class Program
{
static void Main(string[] args)
{
// 各种对象的定义
Excel.Application excel = null;
Excel.Workbooks books = null;
Excel.Workbook book = null;
Excel.Sheets sheets = null;
Excel.Worksheet sheet = null;
Excel.Range cells = null;
Excel.Range range = null;
// 取得文件夹
string folderPath = @"C:UsersxyyDesktopFolder";
// 取得文件夹中扩展名为[.xlsx]的文件
string[] files = Directory.GetFiles(Path.GetFullPath(folderPath), "*.xlsx");
try
{
// 启动Excel
excel = new Excel.Application();
// Workbooks对象的初始化
books = excel.Workbooks;
// 对文件夹中的各个文件进行以下处理
foreach (string file in files)
{
try
{
// 打开文件
book = books.Open(file);
// 选中文件里的所有表
sheets = book.Worksheets;
// 选中第一个表
sheet = sheets[1];
// 选中第一个表的所有单元格
cells = sheet.Cells;
// 选中单元格[2,1]
// range = sheet.Cells[2, 1]
// 注意上面这种写法会产生sheet.Cells和sheet.Cells[2, 1]这两个Excel.Range对象
// 其中一个对象无法得到释放,会导致Excel进程残留问题
range = cells[2, 1];
// 将单元格[2,1]的文字设置成test
range.Value = "test";
// 保存文件的修改并关闭
book.Close(true);
// 关闭Excel
excel.Quit();
}
finally
{
// 释放之前定义的对象,每循环一次就要释放一次,不然会导致Excel进程残留问题
Marshal.FinalReleaseComObject(range);
Marshal.FinalReleaseComObject(cells);
Marshal.FinalReleaseComObject(sheet);
Marshal.FinalReleaseComObject(sheets);
Marshal.FinalReleaseComObject(book);
}
}
}
finally
{
// 最后释放books和excel对象
Marshal.FinalReleaseComObject(books);
Marshal.FinalReleaseComObject(excel);
}
}
}
}
4.创建文件
5.运行结果
运行前 运行后
Book1 & Book2 Book1 & Book2
程序运行时强制终了的话,对象未被释放,会导致有残留的Excel进程。
这时再一次运行程序的话,很有可能会出错。
所以先去任务管理器里结束残留的Excel进程,然后再运行。
// 选中所有列
cells = sheet.Columns;
// 选中第2列
range = cells[2];
// 插入3列
for (int i = 0; i < 3; i++)
{
range.Insert();
}
运行前
运行后
// 选中所有单元格 cells = sheet.Cells; // 选中单元格[2, 2] range1 = cells[2, 2]; // 选中单元格[2, 4] range2 = cells[2, 4]; // 选中单元格[2, 2]到单元格[2, 4] range3 = sheet.Range[range1,range2]; // 单元格的结合 range3.Merge();
也可以这么写
// 选中单元格[B2]到[D2] range = sheet.Range["B2:D2"]; // 单元格的结合 range.Merge();
运行前
运行后
// 定义font对象 Excel.Font font = null; // ... 略 // 选中所有单元格 cells = sheet.Cells; // 选择单元格[2,1] range = cells[2, 1]; // 选择单元格[2,1]的font font = range.Font; // 字体改为红色 font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
运行前 运行后
// 定义border对象 Excel.Borders border = null; // ... 略 // 选中所有单元格 cells = sheet.Cells; // 选择单元格[2,2] range = cells[2, 2]; // 选择单元格[2,2]的边框 border = range.Borders; // 边框设置成实线 border.LineStyle = Excel.XlLineStyle.xlContinuous; // 设置边框的宽度 border.Weight = 2d;
运行前 运行后
本文参考了以下资料
- C#: Excelファイルを読み書きする (COM)
- c#でExcelをOpenするとプロセスが残る(Microsoft.Office.Interop.Excel使用)
- Microsoft.Office.Interop.Excel: How to Apply a border to ONE CELL



