前言
網上使用NPOI讀取Excel文件的例子現在也不少,本文就是參考網上大神們的例子進行修改以適應自己需求的。
參考博文
http://www.cnblogs.com/restran/p/3889479.html
本文使用的NPOI版本是 2.1.1.0(.net2.0) 下載鏈接 https://files.cnblogs.com/files/masonblog/NPOI2-1-1DotNet2-0.zip
本例Excel表格 https://files.cnblogs.com/files/masonblog/NPOIExcelTestRun.zip
運行結果


示例代碼
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.IO; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.HSSF.UserModel; namespace CourseMgr { public partial class EntireSchoolCourse : PageBase { BLL.Course _CourseBLL = null; Model.Course _CourseModel = null; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ExportToExcelByTemplate(); } } #region 根據學校課程表模板導出Excel表格 public void ExportToExcelByTemplate() { string sYear1 = base.YearBegin; string sYear2 = base.YearEnd; string sSemester = base.Term; string sYear = sYear1 + "-" + sYear2; try { #region 獲取課程表數據 _CourseModel = new Model.Course { OrgNo = CurrentOperator.OrgNo, YearStr = sYear, Semester = sSemester }; _CourseBLL = new BLL.Course(); DataTable dtResult = _CourseBLL.GetEntireSchoolCourse(_CourseModel); #endregion #region 打開Excel表格模板,並初始化到NPOI對象中 IWorkbook wk = null; string filePath = Server.MapPath(@"~/Upload/CourseExportTemplate/學校課程表模板.xls"); if (!File.Exists(filePath)) { Windows.MessageBox(Page, "導出失敗:課程表模板不存在!", MessageType.Normal); return; } string extension = System.IO.Path.GetExtension(filePath); FileStream fs = File.OpenRead(filePath); if (extension.Equals(".xls")) { //把xls文件中的數據寫入wk中 wk = new HSSFWorkbook(fs); } else { //把xlsx文件中的數據寫入wk中 wk = new XSSFWorkbook(fs); } fs.Close(); #endregion #region 數據處理 //1.讀取Excel表格中的第一張Sheet表 ISheet sheet = wk.GetSheetAt(0); IRow row = null;//數據行 ICell cell = null;//數據行中的某列 //2.添加Excel數據行。處理表格的邊框,沒有數據的數據行就沒有內外邊框。 //獲取數據行數(班級數量) int iCount = dtResult.Rows.Count; for (int i = 0; i < iCount - 1; i++)//循環次數:數據行-1,因為已經默認添加了一行Excel單元行。 { //從第二行復制出新行,主要是單元格的屬性已經在第二行中設置好。 sheet.CopyRow(2, 2 + 1 + i); } //3.填充數據 string sCourceTeacher = string.Empty;//從DataTable中獲取的課程信息 string[] strCourceTeacher = null;//將課程名稱和教師名稱分割開 //3.1從索引2(第三行)開始填充單元格中的數據 for (int i = 2; i < iCount + 2; i++) { //3.2讀取當前行的對象 row = sheet.GetRow(i); if (row != null) { //3.3獲取該行第一列,賦值班級名稱 cell = row.GetCell(0); cell.SetCellValue(dtResult.Rows[i - 2]["GradeName"].ToString() + dtResult.Rows[i - 2]["ClassName"].ToString()); //3.4循環獲取后面列的對象 for (int j = 1; j < row.LastCellNum; j++) { cell = row.GetCell(j); sCourceTeacher = dtResult.Rows[i - 2]["science" + GetWeekDaySectionByInt(j)].ToString(); //3.4.1如果未獲取到該班級星期節次的信息,則賦值\ if (string.IsNullOrEmpty(sCourceTeacher)) { cell.SetCellValue("\\"); } //3.4.2獲取到課程則進行賦值(課程名稱在上,換行,教師名稱在下) else { strCourceTeacher = sCourceTeacher.Split('|'); cell.SetCellValue(strCourceTeacher[0] + "\n" + strCourceTeacher[1]); } } } } #endregion #region 表格導出 System.IO.MemoryStream ms = new System.IO.MemoryStream(); wk.Write(ms); Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode("學校總課程表", System.Text.Encoding.UTF8))); Response.BinaryWrite(ms.ToArray()); Response.End(); #endregion } catch (Exception ex) { LogWrite("導出課程表失敗", ex.ToString(), CurrentOperator.Name, ResourceID); Windows.MessageBox(Page, "導出課程表失敗", MessageType.Normal); } } /// <summary> /// 將列序號轉換為節次和星期 /// </summary> /// <param name="i"></param> /// <returns></returns> public string GetWeekDaySectionByInt(int i) { //i-1 ,因為第一列為標題列 int iWeekDay = (i - 1) / 8; int iSection = (i - 1) % 8; return (iSection + 1).ToString() + (iWeekDay + 1).ToString(); } #endregion } }
