首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >扩展Excel WorkSheet范围

扩展Excel WorkSheet范围
EN

Stack Overflow用户
提问于 2015-09-08 19:08:40
回答 2查看 333关注 0票数 0

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

我是按照microsoft/msdn https://msdn.microsoft.com/en-us/library/ms173186(v=vs.80).aspx推荐的方式来做的。

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

代码语言:javascript
复制
// 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);

但是在我写的函数中

代码语言:javascript
复制
public void Create ExcelFile(List<string> strList);

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

该怎么做呢?

谢谢。

EN

回答 2

Stack Overflow用户

发布于 2015-09-08 20:44:40

由于您使用的是List类型的对象(根据您的要求),因此可以保持起始范围不变,即在本例中,"C1“和end range可以是集合列表中字符串值的计数。

在以List<string> strList作为输入的方法CreateExcelFile中,获取一个如下所示的endRange,您可以在获取范围时使用它。

代码语言:javascript
复制
string endRange = string.Concat("C", strList.Count.ToString());
Range aRange = ws.get_Range("C1", endRange);

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

票数 1
EN

Stack Overflow用户

发布于 2015-09-08 20:42:30

我找到了答案。

这是我的代码:

代码语言:javascript
复制
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++;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32456209

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档