NPOI操作Excel简单示例

摘要:
根据网上的数据,我学习了NPOI操作Excel的基本方法:1。导出到Excel:将标题行合并到中心,设置列宽,并写入列标题和数据。

     根据网上的资料,学习了一下NPOI操作Excel的基本方法:

   1、导出至Excel:标题行合并居中、设置列宽、写入列标题及数据。

    public class ExportToExcel : IHttpHandler //一般处理程序ExportToExcel.ashx
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/x-excel";
            string fileName = HttpUtility.UrlEncode("备份.xls");
            context.Response.AddHeader("Content-Disposition", "attachment; fileName=" + fileName); 
            HSSFWorkbook workbook = new HSSFWorkbook(); //创建一个xls;
            HSSFSheet sheet = workbook.CreateSheet("用户信息"); //创建一个Sheet页
            sheet.SetColumnWidth(3, 50 * 256);  //设置列宽,50个字符宽度。宽度参数为1/256,故乘以256
            string connectString = @"server=.\sqlexpress;database=BookShop; uid=sa; pwd=123456";
            SqlConnection connection = new SqlConnection(connectString);
            connection.Open();
            /******************写入标题行,合并居中*********************/
            HSSFRow row = sheet.CreateRow(0);
            HSSFCell cell = row.CreateCell(0);
            cell.SetCellValue("用户信息");
            HSSFCellStyle style = workbook.CreateCellStyle();
            style.Alignment = HSSFCellStyle.ALIGN_CENTER;
            HSSFFont font = workbook.CreateFont();
            font.FontHeight = 20 * 20;
            style.SetFont(font);
            cell.CellStyle = style;
            sheet.AddMergedRegion(new Region(0,0,0,4));
            /******************写入列标题*********************/
            int rowsNum = 1;  //行号
            row = sheet.CreateRow(rowsNum);
            row.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue("用户名");
            row.CreateCell(1, HSSFCell.CELL_TYPE_STRING).SetCellValue("密码");
            row.CreateCell(2, HSSFCell.CELL_TYPE_STRING).SetCellValue("姓名");
            row.CreateCell(3, HSSFCell.CELL_TYPE_STRING).SetCellValue("电子邮件");
            row.CreateCell(4, HSSFCell.CELL_TYPE_STRING).SetCellValue("用户组编号");
            using (IDbCommand cmd = connection.CreateCommand()) ;
            {
                cmd.CommandText = "select * from Users";
                using (IDataReader reader = cmd.ExecuteReader())
                {
                    rowsNum = 2;  //行号
                    while (reader.Read())
                    {
                        //根据字段名找出ID
                        string LoginId = reader.GetString(reader.GetOrdinal("LoginId"));
                        string LoginPwd = reader.GetString(reader.GetOrdinal("LoginPwd"));
                        string Name = reader.GetString(reader.GetOrdinal("Name"));
                        string Mail = reader.GetString(reader.GetOrdinal("Mail"));
                        int  userRoleId= reader.GetInt32(reader.GetOrdinal("UserRoleId"));
                        /******************写入字段值*********************/
                        row = sheet.CreateRow(rowsNum);
                        row.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue(LoginId);
                        row.CreateCell(1, HSSFCell.CELL_TYPE_STRING).SetCellValue(LoginPwd);
                        row.CreateCell(2, HSSFCell.CELL_TYPE_STRING).SetCellValue(Name);
                        row.CreateCell(3, HSSFCell.CELL_TYPE_STRING).SetCellValue(Mail);
                        row.CreateCell(4, HSSFCell.CELL_TYPE_STRING).SetCellValue(userRoleId);           //整型数据          
                        rowsNum++;
                    }
                }
            }

            workbook.Write(context.Response.OutputStream);  //输出到流中

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

在其他页面调用:

<a href="http://t.zoukankan.com/ExportToExcel.ashx">导出到Excel</a>

2、读取Excel表格数据至DataTable中

2.1 判断文件类型

<script type="text/javascript">
      function checkType()
      {     
        //得到上传文件的值
        var fileName=document.getElementById("FileUpLoad1").value;   
        //返回String对象中子字符串最后出现的位置.
        var seat=fileName.lastIndexOf("."); 
        //返回位于String对象中指定位置的子字符串并转换为小写.
        var extension=fileName.substring(seat).toLowerCase();     
        //判断允许上传的文件格式      
        //var allowed=[".jpg",".gif",".png",".bmp",".jpeg"];
        var allowed=[".xls"];
        for(var i=0;i<allowed.length;i++){
            if(!(allowed[i]!=extension)){
                return true;
            }
        }
        alert("不支持"+extension+"格式");
        return false;
      }
    </script>

2.2 读取Excle表格,导入至DataTable          

            if (FileUpload1.HasFile)
            {
                //string fileName = Server.MapPath("~/Export/") + FileUpload1.FileName;
                //FileUpload1.PostedFile.SaveAs(fileName);

                try
                {
                    //DataTable dt = ExcelHelper.Import(fileName, 0, 1);  //Excel表格第0行为表头、第1行为列名。
                    DataTable dt = ExcelHelper.Import(FileUpload1.FileContent, 0, 1);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
                catch (Exception ex)
                {
                    JScript.Alert(ex.Message);
                    JScript.Alert("Excel表格格式有误!");
                }

         }

免责声明:文章转载自《NPOI操作Excel简单示例》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇反序列化漏洞安卓作为udp服务器,PC作为客户端,仅监听下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Java实现 “ 将数字金额转为大写中文金额 ”

前言:输入数字金额参数,运行程序得到其对应的大写中文金额;例如:输入 12.56,输出 12.56 : 壹拾贰元伍角陆分;重点来了:本人亲测有效。 奉上代码:/*** @Title: ConvertUpMoney* @Description: 将数字金额转换为大写中文金额* @date: 2019年6月18日 下午10:52:27*/public clas...

WinForm控件设计:DataGridView的行统计实现 原文来自:http://www.cnblogs.com/yyj/archive/2010/10/21/1857518.html

//**************************************////////////////////////////////         #region 显示统计列        /// <summary>        /// 显示DataGridView的统计信息        /// </summary>...

String和datetime在SQL中和在C#中相互转换方法总结

String和datetime之间相互转换方法总结: SQL中的转换方法: 一,将string转换为datetime,主要是使用Convert方法, 方法,Convert(datetime [ ( length ) ] , expression, [style])           如: convert(datetime,Datetime.Now,120...

java的输入输出

0x01:输出流 java常用的输出语句有下面三种: System.out.println();//换行打印,输出之后会自动换行  System.out.print();//不换行打印 System.out.printf();//按格式输出 0x02:输出示例 public class test { public static void...

Delphi7中 string, AnsiString, Utf8String,WideString的区别分析(转)

Windows系统上的 Notepad.exe 打开文件后,点击“文件”菜单中的“另存为”命令,会跳出一个对话框,在最底部有一个“编码”的下拉条。里面有四个选项:ANSI,Unicode,Unicode big endian 和 UTF-8。1)ANSI是默认的编码方式。对于英文文件是ASCII编码,对于简体中文文件是GB2312编码(只针对Windows...

动态创建Fastreport

动态创建Fastreport 动态创建Fastreport分以下几个步骤: 1.首先清空Fastreport,定义全局变量,并加载数据集frReport.Clear;frReport.DataSets.Add(frxDBDataset1);DataHeight :=28;DataWidth :=80;FirstTop := 50;FirstLeft :=...