==标题==
|-----------------------------|
| C#编程:VSTO在Excel工作表中输出List数据 |
==正文==
一、问题:
我想把C#中的List<T>输出到Excel工作表中
二、思路方法:
(1)用程序创建一个List<T>
(2)输出到当前工作表
三、代码:
cs
Excel.Application xlsApp = Globals.ThisAddIn.Application;
Excel.Workbook wbk = xlsApp.ActiveWorkbook;
Excel.Worksheet sht = xlsApp.ActiveSheet;
var dataList = new List<dynamic>();
Random random = new Random();
List<string> titleList = new List<string> { "序号", "单位", "成绩" };
dataList.Add(titleList);
for (int i = 0; i < 20; i++)
{
List<dynamic> OneList = new List<dynamic>();
for (int j = 0; j < 3; j++)
{
OneList.Add(i+1);
OneList.Add("单位" + random.Next(1, 4).ToString("00"));
OneList.Add(random.Next(1, 101));
}
dataList.Add(OneList);
};
for (int i = 0; i < dataList.Count; i++)
{
for (int j = 0; j < 3; j++)
{
sht.Cells[i+1, j+1].value = dataList[i][j];
}
}
sht.UsedRange.HorizontalAlignment = Excel.Constants.xlCenter;
sht.UsedRange.VerticalAlignment = Excel.Constants.xlCenter;
四、解析:
(1)先创建一个dataList
(2)先写入标题 { "序号", "单位", "成绩" };
(3)再写入20行数据
(4)输出到工作表
五、效果:
==The end==
==合集==
===若有用,请转发免费学习===
关注看更多文章