使用NPOI读取Excel表格内容并进行修改

前言

网上使用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] + "
" + 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
    }
}
原文地址:https://www.cnblogs.com/masonblog/p/7097439.html