第一步:项目中加入引用。
在鼠标右击项目,点击【添加】弹出菜单列表,选择【项目引用】弹出【引用管理器】对话框,选择【COM】-【Microsoft Excel 16.0 Object Library】,如图所示:
第二步,编辑相关代码
文件头加 :using MSExcel = Microsoft.Office.Interop.Excel;
打开excel文件:
excelApp = new MSExcel.Application();
excelApp.Visible = false;// 设置EXCEl打开后是否可见。true:可见;false:不可见
MSExcel.Workbooks wbs = excelApp.Workbooks;
MSExcel.Workbook wb = wbs.Add(Missing.Value);// 打开临时文件
导入数据:
MSExcel.Worksheet excelSheet = workbook.Sheets[1];//定义一个新的工作表,获取excel 文件中的第一张工作表
excelSheet.Activate();// 激活工作表
excelSheet.Cells[1, 1] = "学生ID";
excelSheet.Cells[1, 2] = "姓名";
excelSheet.Cells[1, 3] = "性别";
excelSheet.Cells[1, 4] = "年龄";
excelSheet.Cells[1, 5] = "年级";
excelSheet.Cells[1, 6] = "总分";
int index = 1;
foreach (var item in studentList)
{
int rowIndex = ++index;
excelSheet.Cells[rowIndex, 1] = item.Id;// ID
excelSheet.Cells[rowIndex, 2] = item.Name;
excelSheet.Cells[rowIndex, 3] = item.Sex;
excelSheet.Cells[rowIndex, 4] = item.Age;
excelSheet.Cells[rowIndex, 5] = item.Class;
excelSheet.Cells[rowIndex, 6] = item.Score;
}
保存到指定的excell文件:
wb.SaveAs(excelFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlLocalSessionChanges, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
wb.Close();// 关闭文档
wbs.Close();// 关闭工作薄
excelApp.Quit(); // 关闭excel应用程序
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);