【C#】【EXCEL】将grasshopper中指定列数据写入EXCEL中

发布于:2024-03-14 ⋅ 阅读:(80) ⋅ 点赞:(0)
using System;
using System.Collections.Generic;
using Excel = Microsoft.Office.Interop.Excel;

public void RunScript(bool build, List<object> data, string filePath, string sheetName, string columnLetter)
{
    if (build)
    {
        WriteToExcel(data, filePath, sheetName, columnLetter);
    }
}

public static void WriteToExcel(List<object> data, string filePath, string sheetName, string columnLetter)
{
    Excel.Application excelApp = new Excel.Application();
    Excel.Workbook workbook = excelApp.Workbooks.Open(filePath);
    Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[sheetName];

    int rowIndex = 1;
    foreach (var item in data)
    {
        worksheet.Range[columnLetter + rowIndex.ToString()].Value = item;
        rowIndex++;
    }

    workbook.Save();
    workbook.Close();
    excelApp.Quit();

    ReleaseObject(worksheet);
    ReleaseObject(workbook);
    ReleaseObject(excelApp);
}

private static void ReleaseObject(object obj)
{
    System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
    obj = null;
    System.GC.Collect();
}

主要部分:

  1. RunScript 方法: 接受 build 参数来控制是否执行写入 Excel 的操作,如果 buildtrue,则调用 WriteToExcel 方法。

  2. WriteToExcel 方法: 打开指定的 Excel 文件,将数据写入指定的工作表和列中,然后保存并关闭 Excel 文件。

  3. ReleaseObject 方法: 释放 COM 对象,并强制进行垃圾回收。

代码假设 Excel 文件已经存在,并且工作表也已经存在。它没有处理创建新 Excel 文件或工作表的情况,也没有详细的异常处理。

在使用此代码之前,请确保已安装 Microsoft Office,并在 Grasshopper 中引用 Microsoft.Office.Interop.Excel 库。
在这里插入图片描述