扩展Excel工作表范围

我需要通过C#代码创build一个Excel文件。

我这样做是由微软/ 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函数参数中得到的对象的数量。

怎么做?

谢谢。

由于您正在使用Listtypes的对象(根据您的要求),您可以保持开始范围不变,即在这种情况下,“C1”和结束范围可以是“集合列表”中string值的计数。

在你的方法CreateExcelFileList<string> strList作为input,得到一个endRange,如下所示,当你得到Range时你可以使用它。

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

我希望这可以解决你的问题。

我find了答案。

这是我的代码:

 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++; }