先看运行结果→运行结果
开发环境
Microsoft Visual Studio Community Microsoft .NET Framework 4.8.04084Microsoft Excel开发语言
C#1.新建项目
新建「C#控制台应用程序」项目,参照以下内容
快速入门:使用 Visual Studio 创建第一个 C# 控制台应用
2.添加COM引用
添加「Microsoft Excel 16.0 Object Library」COM引用,只找到一篇简单易懂的日语文章
在 .NET 5 项目中添加 COM 引用
3.代码
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:\Users\xyy\Desktop\Folder";// 取得文件夹中扩展名为[.xlsx]的文件string[] files = Directory.GetFiles(Path.GetFullPath(folderPath), "*.xlsx");try{// 启动Excelexcel = 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]的文字设置成testrange.Value = "test";// 保存文件的修改并关闭book.Close(true);// 关闭Excelexcel.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
6.错误处理
程序运行时强制终了的话,对象未被释放,会导致有残留的Excel进程。
这时再一次运行程序的话,很有可能会出错。
所以先去任务管理器里结束残留的Excel进程,然后再运行。
7.其他操作
7.1.插入列
// 选中所有列cells = sheet.Columns;// 选中第2列range = cells[2];// 插入3列for (int i = 0; i < 3; i++){range.Insert();}
运行前
运行后
7.2.合并单元格
// 选中所有单元格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();
运行前
运行后
7.3.更改文本颜色
// 定义font对象Excel.Font font = null; // ... 略// 选中所有单元格cells = sheet.Cells;// 选择单元格[2,1]range = cells[2, 1];// 选择单元格[2,1]的fontfont = range.Font;// 字体改为红色font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
运行前 运行后
7.4.加边框
// 定义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
如果觉得《使用Microsoft.Office.Interop.Excel批量编辑Excel文件》对你有帮助,请点赞、收藏,并留下你的观点哦!