基于.NET 8.0,C#中Microsoft.Office.Interop.Excel来操作office365的excel

开发环境:

Visual Studio 2022 

office365

项目模板:WPF应用程序

框架:.NET 8.0

依赖:Microsoft.Office.Interop.Excel

注意:

1.使用Microsoft.Office.Interop.Excel库时,服务器或电脑里面必须安装得有Excel

管理Nuget程序包中Microsoft.Office.Interop.Excel目前没有16.0版本(2024.10月),所以不能对office365使用。以下是版本对应关系。

Microsoft.Office.Interop.Excel版本

对应的Excel版本
14.0.0Excel 2010 (Office 2010)
15.0.0Excel 2013 (Office 2013)
16.0.0Excel 2016、Excel 2019、Excel 365 (Office 2016, Office 2019, Office 365)

在Visual Studio 2022 中导入Microsoft.Office.Interop.Excel16.0版本的依赖:

打开COM引用

勾选Microsoft Excel 16.0 Object Library后确定。

代码:

1.导入依赖:

using System;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

2.基本框架:

var excelApp = new Excel.Application();
string excel_file_path = @"C:\path\to\your\file.xlsx";
Excel.Workbook workbook = excelApp.Workbooks.Open(excel_file_path);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];//操作sheet1
try{
    /*
    具体对excel的添加操作代码
    */
    workbook.Save();// 保存更改
}
catch (Exception ex) {
    Debug.WriteLine($"发生错误: {ex.Message}");
}
finally { // 确保释放 COM 对象
    if (workbook != null) { 
        workbook.Close(false);
        Marshal.ReleaseComObject(workbook);
}
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
// 强制垃圾回收以确保所有 COM 对象被清理
GC.Collect();
GC.WaitForPendingFinalizers();

3.单元格读写

worksheet.Cells[1, 1] = "1"; // 行1,列1,即A1单元格写入数字1
string cellValue = worksheet.Cells[1, 1].Value.ToString(); // 行1,列1,即读取A1单元格
string cellValue2 = worksheet.Cells[1, "A"].Value.ToString(); // 行1,A列,即读取A1单元格

4.excel转PDF

导入依赖

using System.IO;

代码在workbook.Save();// 保存更改 后执行

 string pdfFilePath = System.IO.Path.ChangeExtension(excel_file_path, ".pdf");//将excel后缀名改为PDF
workbook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, pdfFilePath);//另存为PDF

5.删除表格所有图片

foreach (Excel.Shape shape in worksheet.Shapes)// 获取工作表中的所有图片
    {
    shape.Delete();
    }

6.删除列

int startColumn = 39; // 从39列开始删除后面的所有列
Excel.Range rangeToDelete = worksheet.Range[worksheet.Cells[1, startColumn + 1], worksheet.Cells[worksheet.Rows.Count, worksheet.Columns.Count]];
rangeToDelete.Delete(Excel.XlDeleteShiftDirection.xlShiftToLeft); 

拓展:

针对大批写入excel单元格数据时,构建了一个便利的框架,通过传递List<List<string>>的方式,循环调用修改。这里构建了一个列表 List<List<string>> excel_write_list,列表excel_write_list中包含子列表,子列表内容依次放入列表名,行,列,数据,类型均为string。通过excel_write_list.Add向主列表增加新的修改写入即可。调用excel_write函数后,该函数会依次读取主列表中的每个子列表,执行修改内容。

using System.Runtime.InteropServices;
using System.Diagnostics;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;

public class Test
{
    public void main() {
        string excel_path = @"C:\1.xls";//excel地址
        List<List<string>> excel_write_list = new List<List<string>>();
        excel_write_list.Add(new List<string> { "sheet1", "4", "K", "数据" });//子表内容为[sheet名,行,列,输入内容]
        excel_write(excel_path, excel_write_list);
    }
    private void excel_write(string excel_path, List<List<string>> excel_write_list)
    {
        var excelApp = new Excel.Application();
        Excel.Workbook workbook = excelApp.Workbooks.Open(excel_path);
        try
        {
            foreach (List<string> i in excel_write_list)
            {
                workbook.Worksheets[i[0]].Cells[i[1], i[2]] = i[3];
            }
            workbook.Save();// 保存更改
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"发生错误: {ex.Message}");
        }
        finally
        { // 确保释放 COM 对象
            if (workbook != null)
            {
                workbook.Close(false);
                Marshal.ReleaseComObject(workbook);
            }
            excelApp.Quit();
            Marshal.ReleaseComObject(excelApp);// 强制垃圾回收以确保所有 COM 对象被清理
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

幽默小书生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值