关闭EXCEL进程
//导入Windows类库,可以获得进程ID
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowsThreadProcesId( IntPtr bwnd,out int ID );
/// <summary>
/// 从Excel 获取学生数据
/// </summary>
/// <param name="filePath">带完整路径的Excel文件名</param>
/// <param name="sheetName">工作表名字</param>
/// <returns>学生实体集合</returns>
public List<Student> GetStudentsFromExcel(string filePath, string sheetName)
{
List<Student> students = new List<Student>();
Microsoft.Office.Interop.Excel.Application excel =
new Microsoft.Office.Interop.Excel.Application();
Worksheet sheet = null;
Range rNo = null;
try
{
excel.Workbooks.Open(filePath);//打开Excel 文件
foreach (Worksheet wsheet in excel.ActiveWorkbook.Sheets)
{
if (wsheet.Name == sheetName)
{
sheet = wsheet;
break;
}
}
//读取单元格数据
if (sheet != null)
{
int row = 2;//当前行号
while (true)
{
//如果碰到学号为空的行,则停止读取数据
rNo = sheet.Cells[row, 1] as Range;
if (rNo.Text.ToString().Trim().Length == 0)
{
break;
}
Student stu = new Student();
//学号
Range rContent = sheet.Cells[row, 1] as Range;
stu.StudentNo = Convert.ToInt32(rContent.Text.ToString().Trim());
//密码
rContent = sheet.Cells[row, 2] as Range;
stu.LoginPwd = rContent.Text.ToString().Trim();
//姓名
rContent = sheet.Cells[row, 3] as Range;
stu.StudentName = rContent.Text.ToString().Trim();
//性别
rContent = sheet.Cells[row, 4] as Range;
stu.Gender = rContent.Text.ToString().Trim() == "男" ? true : false;
//年级
rContent = sheet.Cells[row, 5] as Range;
stu.GradeId = new GradeManager().GetGradeId(rContent.Text.ToString().Trim());
//电话
rContent = sheet.Cells[row, 6] as Range;
stu.Phone = rContent.Text.ToString().Trim();
//地址
rContent = sheet.Cells[row, 7] as Range;
stu.Address = rContent.Text.ToString().Trim();
//出生年月日
rContent = sheet.Cells[row, 8] as Range;
stu.BornDate = Convert.ToDateTime(rContent.Text.ToString().Trim());
//邮箱
rContent = sheet.Cells[row, 9] as Range;
stu.Email = rContent.Text.ToString().Trim();
//身份证号
rContent = sheet.Cells[row, 10] as Range;
stu.IdentityCard = rContent.Text.ToString().Trim();
students.Add(stu);
row += 1;
}
}
excel.Visible = true;
//关闭WorkBook
excel.ActiveWorkbook.Close();
//关闭Excel
excel.Quit();
}
finally
{
////主动释放COM对象
//Marshal.ReleaseComObject(sheet);
//Marshal.ReleaseComObject(excel);
//Marshal.ReleaseComObject(rNo);
////对象引用设置null
// sheet = null;
// excel = null;
// rNo = null;
////通过垃圾收集器回收对象
// GC.Collect();
//通过Hwnd 获得当前Excel Application对象的句柄对象
IntPtr t = new IntPtr(excel.Hwnd);
int k = 0;
//调用方法获取进程ID
GetWindowsThreadProcesId(t,out k);
//由进程ID获取进程
Process p = Process.GetProcessById(k);
p.Kill();//关闭进程
}
return students;
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。