C#中使用NPOI将DataTable导出到Excel文件

需要引入dll(可以选择.net2.0、.net3.5或者.net4.0的dll) 点击下载DLL      Npoi使用手册

NopiExcel.cs类

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.SS.UserModel;
using System.Collections;
using System.Security.Cryptography;


namespace Common
{
    public class NPOIExcel
    {
        /// 
        /// 将Excel读入到HashTable
        /// 
        /// 文件路径
        /// 相应的DataTable
        public static Hashtable ConvertToDataTable(string path)
        {
            if (path == "") return null;
            HSSFWorkbook hssfworkbook=null;
            try
            {
                using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    hssfworkbook = new HSSFWorkbook(file);
                }
            }
            catch
            {
                return null;
            }
           
            Hashtable ht = new Hashtable();
            for (int e = 0; e < (int)hssfworkbook.Count; e++)
            {
                //获取excel的第一个sheet
                ISheet sheet = hssfworkbook.GetSheetAt(e);
                string sheetName = hssfworkbook.GetSheetName(e);
                DataTable dt = new DataTable();
                //获取sheet的首行
                IRow headerRow = sheet.GetRow(0);


                //一行最后一个方格的编号 即总的列数
                int cellCount = headerRow.LastCellNum;


                for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                {
                    DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                    dt.Columns.Add(column);
                }
                //最后一列的标号  即总的行数
                int rowCount = sheet.LastRowNum;


                for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    DataRow dataRow = dt.NewRow();


                    for (int j = row.FirstCellNum; j < cellCount; j++)
                    {
                        if (row.GetCell(j) != null)
                            dataRow[j] = row.GetCell(j).ToString();
                        else dataRow[j] = "";
                    }


                    dt.Rows.Add(dataRow);
                }               
                sheet = null;
                ht.Add(sheetName, dt);
            }
            hssfworkbook = null;
            return ht;
        }


        /// 
        /// DataTable导出到Excel文件  
        /// 
        /// 源DataTable
        /// 表头文本
        /// 保存位置
        public static void DataTableToExcel(Hashtable ht, string strFileName)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();


            foreach (DictionaryEntry de in ht)
            {
                DataTable dt = (DataTable)de.Value;
                string sheetName = (string)de.Key;
                ISheet sheet = workbook.CreateSheet(sheetName);
                IRow dataRow = sheet.CreateRow(0);
                foreach (DataColumn column in dt.Columns)
                {
                    dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                }


                //填充内容  
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dataRow = sheet.CreateRow(i + 1);
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        dataRow.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
                    }
                }
            }
            workbook.Write(new FileStream(strFileName, FileMode.Create, FileAccess.Write));            
        }
    }
}


后台执行操作

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business;
using Common;//nopiExcel放在namespace Commom下
using System.Collections;
using System.Data;
namespace CourseCaculate.PrimaryC
{
    public partial class PrimaryCExport : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
              
            }
        }     

       
        /// 
        /// 导出
        /// 
        /// 
        /// 
        public void btnExport_Click(object sender, EventArgs e)
        {
           
            DataTable dt = CourseMarksDAL.GetDataTableLike();

            IList toEraseList = new List();
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                if (!InNameList(dt.Columns[i].ColumnName))
                {
                    //dt.Columns.RemoveAt(i);
                    toEraseList.Add(dt.Columns[i].ColumnName);
                }
            }
            foreach (string s in toEraseList)
            {
                dt.Columns.Remove(s);
            }
            dt.Columns["TicketNum"].ColumnName = "准考证号";
            dt.Columns["StuID"].ColumnName = "学号";
            dt.Columns["StuName"].ColumnName = "姓名";
            dt.Columns["ProfeName"].ColumnName = "专业名称";           
            dt.Columns["ExamMarks"].ColumnName = "笔试成绩";
          
            string fileName = "C语言成绩.xls";
            NPOIHelper.ExportByWeb(dt, fileName);
        }    

        /// 
        /// 判断是否为列名
        /// 
        /// 
        /// 
        public bool InNameList(string name)
        {
            string[] nameList = { "TicketNum", "StuID", "StuName", "ProfeName", "ExamMarks"};
            for (int i = 0; i < (int)nameList.Length; i++)
            {
                if (name == nameList[i])
                {
                    return true;
                }
            }
            return false;
        }

        
    }
}


 
  


你可能感兴趣的:(C#/ASP,excel,npoi)