我需要用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函数参数中获得的对象数。
该怎么做呢?
谢谢。
发布于 2015-09-08 20:44:40
由于您使用的是List类型的对象(根据您的要求),因此可以保持起始范围不变,即在本例中,"C1“和end range可以是集合列表中字符串值的计数。
在以List<string> strList作为输入的方法CreateExcelFile中,获取一个如下所示的endRange,您可以在获取范围时使用它。
string endRange = string.Concat("C", strList.Count.ToString());
Range aRange = ws.get_Range("C1", endRange);我希望这能解决你的问题。
发布于 2015-09-08 20:42:30
我找到了答案。
这是我的代码:
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++;
}https://stackoverflow.com/questions/32456209
复制相似问题