栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

使用Microsoft.Office.Interop.Excel批量编辑Excel文件

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Microsoft.Office.Interop.Excel批量编辑Excel文件

先看运行结果  →  运行结果

开发环境
  • Microsoft Visual Studio Community 2019
  • Microsoft .NET Framework 4.8.04084
  • Microsoft Excel 2016
开发语言
  • 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: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
    

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]的font
font = 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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/983976.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号