using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.HSSF.UserModel;
using System.IO;
using System.Windows.Forms;
using Model;
using NPOI.XSSF.UserModel;//调用NPOI引用
namespace DAL.Helper
{
public class PrintHelper
{
public void PrintMsg(StudentModel objStudentModel)
{
//打开事先编写好的Excle模板,当前权限为只读
FileStream theExcel = new FileStream(@"E:\rcmeng\source\Test Program\AppOfStudents\AppOfStudents\bin\Debug\StudentInfo.xlsx", FileMode.Open, FileAccess.Read);
//调用Excle模板,并新建一个工作簿,计算机中如果Excle版本为2007以下则为HSSFWorkbook,若为2007以上,则为XSSFWorkbook
XSSFWorkbook theStudentInfo = new XSSFWorkbook(theExcel);
//新建或获取一个工作表,由于已经事先编写好了模板,可以直接调用模板中的工作表,此处所调用的工作表名称为“info”
XSSFSheet theStudentInfoSheet = (XSSFSheet)theStudentInfo.GetSheet("Info");
//NPOI操作,将封装好的数据(objStudentModel)依次填充进该Excle中
XSSFCell cellId = (XSSFCell)theStudentInfoSheet.GetRow(3).GetCell(3);
cellId.SetCellValue(objStudentModel.StudentId);
XSSFCell cellName = (XSSFCell)theStudentInfoSheet.GetRow(3).GetCell(5);
cellName.SetCellValue(objStudentModel.StudentName);
XSSFCell cellGender = (XSSFCell)theStudentInfoSheet.GetRow(3).GetCell(7);
cellGender.SetCellValue(objStudentModel.Gender);
XSSFCell cellClassName = (XSSFCell)theStudentInfoSheet.GetRow(5).GetCell(3);
cellClassName.SetCellValue(objStudentModel.ClassName);
XSSFCell cellPhoneNumber = (XSSFCell)theStudentInfoSheet.GetRow(5).GetCell(5);
cellPhoneNumber.SetCellValue(objStudentModel.PhoneNumber);
XSSFCell cellStudentAddress = (XSSFCell)theStudentInfoSheet.GetRow(7).GetCell(3);
cellStudentAddress.SetCellValue(objStudentModel.StudentAddress);
//保存文件
//提示用户保存文件的位置(引用的是IO的扩展文件)
SaveFileDialog saveFile = new SaveFileDialog();
//新文件默认扩展名,Excle文件可为.xlsx或.xls
saveFile.DefaultExt = ".xlsx";
//保存类型设置项(比较懒,所以只写了一个设置项)
saveFile.Filter = "Excel文件|*.xlsx";
//新文件名默认设置为“学员信息”
string fileName = "学员信息";
//将已设置好的默认名称赋值
saveFile.FileName = fileName;
//弹出对话框
saveFile.ShowDialog();
//可进行文件名修改,并保存
fileName = saveFile.FileName;
//点击取消
if (fileName.IndexOf(":") < 0)
{
return;
}
//点击确定
if (fileName != "")
{
//新建文件流,创建一个新文件
FileStream newFile = new FileStream(saveFile.FileName, FileMode.Create);
theStudentInfo.Write(newFile);
//关闭文件流
newFile.Close();
//GC垃圾回收机制
GC.SuppressFinalize(this);
}
}
}
}