动态填充excel文件

时间:2015-01-20 13:12:25

标签: c# excel

我正在尝试动态创建一个excel文件。这是我的代码,但我不知道如何在每个单元格中写入特定的字符串。我只想在所有单元格中使用相同的字符串。

示例(我试图遵循的那个)在每个单元格中写入相同的文本,但我想要更改

using Microsoft.Office.Interop.Excel;

Range aRange = ws.get_Range("A1", "A"+words.Length);
//Obtain the range
if (aRange == null){ 
    Console.WriteLine("Could not get a range. Check to be sure you have the correct versions of the office DLLs.");
}

Object[] args = new Object[1];
//   args[0] = 6; <- this is the default

for (var i = 0; i < words.Length; i++) {
   args[0] = words[i];
}
aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args);

我已经添加了for循环,但我不知道如何将其写入每个单元格,每个单词。

编辑:在所有行中,系统写入单词[last]

1 个答案:

答案 0 :(得分:1)

您的对象数组需要与单词数相同。

Object[] args = new Object[words.Length];

然后,您可以在for循环内正确地将单词分配给该数组的项目。

args[i] = words[i];

在您的代码中,您将在循环的每次迭代中覆盖数组中的 only 项的值(args[0]),最后以最后一个单词作为值。< / p>