扩展Excel工作表范围

时间:2015-09-08 11:08:40

标签: c# excel

我需要用C#代码创建一个Excel文件。

我按照microsoft / msdn https://msdn.microsoft.com/en-us/library/ms173186(v=vs.80).aspx

推荐的方式进行操作

在msdn示例中,单元格范围是固定的:

// Select the Excel cells, in the range c1 to c7 in the worksheet.
Range aRange = ws.get_Range("C1", "C7");

if (aRange == null)
{
    Console.WriteLine("Could not get a range. Check to be sure you have the correct versions of the office DLLs.");
}

// Fill the cells in the C1 to C7 range of the worksheet with the number 6.
Object[] args = new Object[1];
args[0] = 6;
aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args);

但在我的作品中,我正在写作

public void Create ExcelFile(List<string> strList);

我需要将行数增加到List函数参数中获得的对象数。

怎么做?

感谢。

2 个答案:

答案 0 :(得分:1)

由于您使用的是List类型的对象(根据您的要求),您可以保持起始范围不变,即,在这种情况下,“C1”和结束范围可以是集合列表中字符串值的计数

在方法CreateExcelFile中输入List<string> strList作为输入,获取如下的endRange,并在获得范围时使用相同的内容。

string endRange = string.Concat("C", strList.Count.ToString());
Range aRange = ws.get_Range("C1", endRange);

我希望这能解决你的问题。

答案 1 :(得分:0)

我找到了答案。

这是我的代码:

int i = 1;
foreach (ItemDetailsPrice item in strList)
{
    //xlWorkSheet.Cells[i, 0] = new Cell("Code");
    aRange = (Excel.Range)xlWorkSheet.Cells[i, 1];
    args[0] = plant;
    aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args);

    aRange = (Excel.Range)xlWorkSheet.Cells[i, 2];
    args[0] = item.ItemCode;
    aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args);

    aRange = (Excel.Range)xlWorkSheet.Cells[i, 3];
    args[0] = item.ItemName;
    aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args);

    aRange = (Excel.Range)xlWorkSheet.Cells[i, 4];
    args[0] = item.ItemPrice;
    aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args);

    aRange = (Excel.Range)xlWorkSheet.Cells[i, 5];
    args[0] = "Y";
    aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args);

    i++;
}