首先创建一个带有图表的Excel模板,如下 :
接下来引用NPOI的dll,直接用NuGet安装,后面别忘了引用命名空间哦。
模板有了之后就可以直接上代码了
//信息类
public class Infos
{
//平均分 及格人数 及格率
public int i1 { get; set; }
public int i2 { get; set; }
public double i3 { get; set; }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.HSSF.UserModel;//引用NPOI的dll
using NPOI.DDF;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
List<Infos> list=new List<Infos>() {
new Infos { i1=99,i2=10,i3=0.48 },
new Infos { i1=88,i2=18,i3=0.68 },
new Infos { i1=77,i2=20,i3=0.28 },
new Infos { i1=95,i2=22,i3=0.94 },
new Infos { i1=92,i2=70,i3=0.50 },
};
string filePath = string.Empty;
HSSFWorkbook workbook = null;//Excel实例
HSSFSheet sheet1 = null;//表实例
HSSFRow row = null; //行
int nowRowNum = 1;//当前行2,表头第一行
if (list.Count < 1)
{
Console.WriteLine("没有数据");
return;
}
//模板路径 打开模板 bin\Debug\temp\Excels.xls
string excelTempPath = System.Environment.CurrentDirectory + @"\temp\Excels.xls";
//string excelTempPath = "C:/Users/ironman/Desktop/WorkFiles/Excels.xls";
//读取Excel模板
using (FileStream fs = new FileStream(excelTempPath, FileMode.Open, FileAccess.Read))
{
workbook = new HSSFWorkbook(fs);
}
//获取sheet1
sheet1 = workbook.GetSheetAt(0);
for (int i = 0; i < list.Count; i++)
{
//获取当前行
row = sheet1.GetRow(nowRowNum);
//给行的单元格填充数据
row.GetCell(1).SetCellValue(list[i].i1);
row.GetCell(2).SetCellValue(list[i].i2);
row.GetCell(3).SetCellValue(list[i].i3);
nowRowNum++;
}
Console.WriteLine("保存?请输入路径,退出输入exit");//请输入绝对路径
string str = Console.ReadLine();
if (str=="exit")
{
return;
}
else
{
//Console.ReadKey();
FileStream file = new FileStream(str + @"\Exceldemos.xls", FileMode.Create);
workbook.Write(file);
file.Close();
}
}
}
}