首页 > 代码库 > asp.net(C#)之NPOI"操作Excel

asp.net(C#)之NPOI"操作Excel

1.首先到网上下载"NPOI.DLL",引用。

2.新建一个操作类“ExcelHelper.cs”:

using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

public class ExcelHelper
{
    public class x2003
    {
        #region Excel2003
        /// <summary>
        /// 将Excel文件中的数据读出到DataTable中(xls)
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static DataTable ExcelToTableForXLS(string file)
        {
            DataTable dt = new DataTable();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                HSSFWorkbook hssfworkbook = new HSSFWorkbook(fs);
                ISheet sheet = hssfworkbook.GetSheetAt(0);

                //表头
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueTypeForXLS(header.GetCell(i) as HSSFCell);
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                        //continue;
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                }
                //数据
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    bool hasValue = http://www.mamicode.com/false;>
3.程序后台主要代码:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Linq;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btn_read_03_click(object o, EventArgs e)
    {
        var dt = ExcelHelper.GetDataTable(Server.MapPath("~/xls_tmp/2003.xls"));
        g1.DataSource = dt;
        g1.DataBind();
    }
    protected void btn_read_07_click(object o, EventArgs e)
    {
        var dt = ExcelHelper.GetDataTable(Server.MapPath("~/xls_tmp/2007.xlsx"));
        g1.DataSource = dt;
        g1.DataBind();
    }
    protected void btn_import_03_click(object o, EventArgs e)
    {
        var name = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random(DateTime.Now.Second).Next(10000);
        var path = Server.MapPath("~/xls_down/" + name + ".xls");
        var dt = new System.Data.DataTable();
        var Columns=Enumerable.Range(1, 10).Select(d => new DataColumn("a"+d.ToString(), typeof(string))).ToArray();
        dt.Columns.AddRange(Columns);
        for (int i = 0; i < 33333; i++)
        {
            var id = Guid.NewGuid().ToString();
            dt.Rows.Add(id, id, id, id, id, id, id, id, id, id);
        }
        ExcelHelper.x2003.TableToExcelForXLS(dt, path);
        downloadfile(path);
    }
    protected void btn_import_07_click(object o, EventArgs e)
    {
        var name = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random(DateTime.Now.Second).Next(10000);
        var path = Server.MapPath("~/xls_down/" + name + ".xlsx");
        var dt = new System.Data.DataTable();
        var Columns = Enumerable.Range(1, 10).Select(d => new DataColumn("a" + d.ToString(), typeof(string))).ToArray();
        dt.Columns.AddRange(Columns);
        for (int i = 0; i < 33333; i++)
        {
            var id = Guid.NewGuid().ToString();
            dt.Rows.Add(id, id, id, id, id, id, id, id, id, id);
        }
        ExcelHelper.x2007.TableToExcelForXLSX(dt, path);
        downloadfile(path);
    }
    void downloadfile(string s_path)
    {
        System.IO.FileInfo file = new System.IO.FileInfo(s_path);
        HttpContext.Current.Response.ContentType = "application/ms-download";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
        HttpContext.Current.Response.Charset = "utf-8";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(file.Name, System.Text.Encoding.UTF8));
        HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
        HttpContext.Current.Response.WriteFile(file.FullName);
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.End();
    }
}


asp.net(C#)之NPOI"操作Excel