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 = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueTypeForXLS(sheet.GetRow(i).GetCell(j) as HSSFCell);
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// 将DataTable数据导出到Excel文件中(xls)
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="file"></param>
        public static void TableToExcelForXLS(DataTable dt, string file)
        {
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            ISheet sheet = hssfworkbook.CreateSheet("Test");

            //表头
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(dt.Columns[i].ColumnName);
            }

            //数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ICell cell = row1.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                }
            }

            //转为字节数组
            MemoryStream stream = new MemoryStream();
            hssfworkbook.Write(stream);
            var buf = stream.ToArray();

            //保存为Excel文件
            using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }
        }

        /// <summary>
        /// 获取单元格类型(xls)
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static object GetValueTypeForXLS(HSSFCell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:
                    return null;
                case CellType.Boolean: //BOOLEAN:
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:
                    return cell.NumericCellValue;
                case CellType.String: //STRING:
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:
                default:
                    return "=" + cell.CellFormula;
            }
        }
        #endregion
    }

    public class x2007
    {
        #region Excel2007
        /// <summary>
        /// 将Excel文件中的数据读出到DataTable中(xlsx)
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static DataTable ExcelToTableForXLSX(string file)
        {
            DataTable dt = new DataTable();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                XSSFWorkbook xssfworkbook = new XSSFWorkbook(fs);
                ISheet sheet = xssfworkbook.GetSheetAt(0);

                //表头
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueTypeForXLSX(header.GetCell(i) as XSSFCell);
                    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 = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueTypeForXLSX(sheet.GetRow(i).GetCell(j) as XSSFCell);
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// 将DataTable数据导出到Excel文件中(xlsx)
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="file"></param>
        public static void TableToExcelForXLSX(DataTable dt, string file)
        {
            XSSFWorkbook xssfworkbook = new XSSFWorkbook();
            ISheet sheet = xssfworkbook.CreateSheet("Test");

            //表头
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(dt.Columns[i].ColumnName);
            }

            //数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ICell cell = row1.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                }
            }

            //转为字节数组
            MemoryStream stream = new MemoryStream();
            xssfworkbook.Write(stream);
            var buf = stream.ToArray();

            //保存为Excel文件
            using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }
        }

        /// <summary>
        /// 获取单元格类型(xlsx)
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static object GetValueTypeForXLSX(XSSFCell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:
                    return null;
                case CellType.Boolean: //BOOLEAN:
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:
                    return cell.NumericCellValue;
                case CellType.String: //STRING:
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:
                default:
                    return "=" + cell.CellFormula;
            }
        }
        #endregion
    }

    public static DataTable GetDataTable(string filepath)
    {
        var dt = new DataTable("xls");
        if (filepath.Last()=='s')
        {
            dt = x2003.ExcelToTableForXLS(filepath);
        }
        else
        {
            dt = x2007.ExcelToTableForXLSX(filepath);
        }
        return dt;
    }
}

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();
    }
}
时间: 2024-10-10 11:54:17

asp.net(C#)之NPOI"操作Excel的相关文章

NPOI操作Excel 003:写入空Excel

对于NPOI操作Excel前面已经有了简单认识(http://blog.csdn.net/yysyangyangyangshan/article/details/42614209).继续来看如何将内容保存至Excel中.根据前面的经验NPOI操作Excel主要的几个对象分别是:workbook,sheet以及sheet内的row和cell.所以保存至Excel也是对这几个对象进行操作.当然我们平时使用Excel时不光要在单元格中保存内容,还要设置单元格的格式以及字体大小等,也就是格式和样式.这些

NPOI操作excel——利用反射机制,NPOI读取excel数据准确映射到数据库字段

> 其实需求很明确,就是一大堆不一样的excel,每张excel对应数据库的一张表,我们需要提供用户上传excel,我们解析数据入库的功能实现. 那么,这就涉及到一个问题:我们可以读出excel的表头,但是怎么知道每个表头具体对应数据库里面的字段呢? 博主经过一段时间的思考与构思,想到一法:现在的情况是我们有excel表A,对应数据库表B,但是A与B具体属性字段的映射关系我们不知.那我们是不是可以有一个A到B的映射文件C呢? 我想,说到这,大家就很明了了... 第一步:为每张excel创建一个与

Npoi操作excel

转载地址:http://www.cnblogs.com/knowledgesea/archive/2012/11/16/2772547.html Npoi操作excel Npoi 简介 1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet:行:Row:单元格Cell. 2.Npoi 下载地址:http://npoi.codeplex.com/releases/view/38113 3.Npoi 学习系列教程推荐:http://www.cnblogs.co

用NPOI操作EXCEL-锁定列CreateFreezePane()

public void ExportPermissionRoleData(string search, int roleStatus) { var workbook = new HSSFWorkbook(); string random = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(100); string fileName = HttpUtility.UrlEncode("sheet"

NPOI操作EXCEL--设置密码及设置只读

有时,我们可能需要某些单元格只读,如在做模板时,模板中的数据是不能随意让别人改的.在Excel中,可以通过“审阅->保护工作表”来完成,如下图:      那么,在NPOI中有没有办法通过编码的方式达到这一效果呢?答案是肯定的. HSSFSheet sheet1 = hssfworkbook.CreateSheet("Sheet1"); HSSFRow row1 = sheet1.CreateRow(0);HSSFCell cel1 = row1.CreateCell(0);HS

C#开发中使用Npoi操作excel实例代码

C#开发中使用Npoi操作excel实例代码 出处:西西整理 作者:西西 日期:2012/11/16 9:35:50 [大 中 小] 评论: 0 | 我要发表看法 Npoi 是什么? 1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet:行:Row:单元格Cell. 2.Npoi 下载地址:http://npoi.codeplex.com/releases/view/38113 3.Npoi 学习系列教程推荐:http://www.cnblogs.com

通过NPOI操作Excel

最近在做的一个项目中需要生成Excel,通过学习使用NPOI实现了相关需求,写了一个简便操作的类,记录如下: public class NPOIHelperForExcel { #region excel文件属性 //作者 public string Author { get; set; } //标题 public string Title { get; set; } //主题 public string Subject { get; set; } //标记 public string Keyw

NPOI操作Excel 002:读取Excel

本文讲述如何通过NPOI来读取Excel.需要准备的dll见:http://blog.csdn.net/yysyangyangyangshan/article/details/42614181环境.net2.0,Excel版本2003.NPOI读取Excel比较简单,只要抓住Excel的几个主要点即可.一般Excel通过这几部分构成的,book,sheet页,然后是sheet页里的行列.读取Excel则是先找到book,然后book内的sheet,之后就根据sheet里的第几行第几列进行读取内容

C#通过NPOI操作Excel

C#操作Excel的方法有很多种,常见的有微软官方的OLE Automation,Apache的POI等.这里介绍的是POI翻译成C#的NPOI. POI是Apache的通过Java操作Office的一个API,可以对Excel,Word,PPT等进行操作,十分的强大.然后就被翻译成C#版本的NPOI了,和log4j与log4net很相似. 好像在NPOI的.net4.0版本之前是不支持office2007及以上的XML格式的,但是最新的版本已经支持了.只需要下载并引用下面五个程序集就能使用了.