gpt4 book ai didi

c# - 如何使用 Excel Dna 设置单元格的值?

转载 作者:太空狗 更新时间:2023-10-30 00:20:01 25 4
gpt4 key购买 nike

我的 Excel DNA 插件中有以下代码

在我的 AutoOpen 方法中,我放入了以下代码:

ExcelIntegration.RegisterUnhandledExceptionHandler(ex => ex.ToString());

我从我的 Excel 工作表中调用了以下函数。

[ExcelFunction(Category = "Foo", Description = "Sets value of cell")]
public static Foo(String idx)
{
Excel.Application app = (Excel.Application)ExcelDnaUtil.Application;
Excel.Workbook wb = app.Workbooks[1];
Excel.Worksheet ws = GetSheet("Main");

// This gives us the row
Excel.Name idxRange = wb.Names.Item("COL_Main_Index");
var row = (int)app.WorksheetFunction.Match(idx, idxRange.RefersToRange, 0);

// Get the Column
Excel.Name buyOrderRange = wb.Names.Item("COL_Main_BuyOrder");
var col = (int)buyOrderRange.RefersToRange.Cells.Column;

// create the range and update it
Excel.Range r = (Excel.Range)ws.Cells[row, col];
r.Value ="Foo";
}

问题是我实际上无法设置任何单元格值。当我调用该方法时,它会在最后一行导致错误。

我的错误处理程序给我以下错误:

{System.Runtime.InteropServices.COMException (0x800A03EC)

我也试过像这样设置单元格值:

        r = (Excel.Range)ws.Cells[12, 22];
const int nCells = 1;
Object[] args1 = new Object[1];
args1[0] = nCells;
r.GetType().InvokeMember("Value2", BindingFlags.SetProperty, null, r, args1);

同样的结果。

谁能指出我在这里可能做错了什么?

最佳答案

实际上,如果您在异步作业中以宏的形式执行此操作,则可以在任何单元格中写入。

简单示例:

using ExcelDna.Integration;
using Excel = Microsoft.Office.Interop.Excel;

[ExcelFunction(Category = "Foo", Description = "Sets value of cell")]
public static Foo(String idx)
{
Excel.Application app = (Excel.Application)ExcelDnaUtil.Application;
Excel.Range range = app.ActiveCell;

object[2,2] dummyData = new object[2, 2] {
{ "foo", "bar" },
{ 2500, 7500 }
};

var reference = new ExcelReference(
range.Row, range.Row + 2 - 1, // from-to-Row
range.Column - 1, range.Column + 2 - 1); // from-to-Column

// Cells are written via this async task
ExcelAsyncUtil.QueueAsMacro(() => { reference.SetValue(dummyData); });

// Value displayed in the current cell.
// It still is a UDF and can be executed multiple times via F2, Return.
return "=Foo()";
}

写入单个单元格:

int row = 5;
int column = 6;
var reference = new ExcelReference(row - 1, column - 1);

ExcelAsyncUtil.QueueAsMacro(() => { reference.SetValue("Foobar"); });

//编辑:仅供引用,您还可以使用:

private void WriteArray(object[,] data)
{
Excel.Application app = (Excel.Application)ExcelDnaUtil.Application;
Excel.Worksheet worksheet= (Excel.Worksheet)app.ActiveWorkbook.ActiveSheet;

Excel.Range startCell = app.ActiveCell;
Excel.Range endCell = (Excel.Range)worksheet.Cells[startCell.Row + data.GetLength(0) - 1, startCell.Column + data.GetLength(1) - 1];

var writeRange = worksheet.Range[startCell, endCell];
writeRange.Value2 = data;
}

然后:

object[,] data = ...;    
ExcelAsyncUtil.QueueAsMacro(() =>
{
WriteArray();
});

关于c# - 如何使用 Excel Dna 设置单元格的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14896215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com