在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#文件解析和处理 → NPOI导出excel+LAYUI+二维码的生成 实例源码

NPOI导出excel+LAYUI+二维码的生成 实例源码

C#文件解析和处理

下载此实例
  • 开发语言:C#
  • 实例大小:3.80M
  • 下载次数:143
  • 浏览次数:2821
  • 发布时间:2017-01-09
  • 实例类别:C#文件解析和处理
  • 发 布 人:zcj123
  • 文件格式:.rar
  • 所需积分:2
 相关标签: NPOI+LAYUI+二维码的生成

实例介绍

【实例简介】

【实例截图】



【核心代码】

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System.Text;
using Newtonsoft.Json;
using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.UI;

namespace ExportExcelDate
{
    /// <summary>
    /// Pint 的摘要说明
    /// </summary>
    public class Pint : IHttpHandler
    {
        private static readonly string imageBasePath = "D:\\PathConfig\\";
        private static readonly string excelBasePath = "D:\\PathConfig\\";
        private HttpContext Context = HttpContext.Current;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string method = context.Request["Method"].ToString();
            MethodInfo methodInfo = this.GetType().GetMethod(method);//利用反射 获取方法
            string result = methodInfo.Invoke(this, null).ToString();//执行获取到的方法
            context.Response.Write(result);
        }
        //实体类
        public class peple {
            public string name { get; set; }
            public string sex { get; set; }
            public string both { get; set; }
            public string add { get; set; }
            

        }
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="QrCodeStr">二维码字符串</param>
        /// <returns></returns>
        public string GetQrCode(string QrCodeStr)
        {
            string FileName = imageBasePath   Guid.NewGuid().ToString()   ".png";
            try
            {
                QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.L);
                QrCode qrCode = new QrCode();
                qrEncoder.TryEncode(QrCodeStr, out qrCode);
                GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);
                using (FileStream stream = new FileStream(FileName, FileMode.Create))
                {
                    renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);
                }
            }
            catch (Exception ex)
            {
                FileName = "";
                throw ex;
            }
            return FileName;
        }
        /// <summary>
        /// 二维码导出到Excel
        /// </summary>
        public void print()
        {
            try
            {
                if (!Directory.Exists(imageBasePath))
                {
                    Directory.CreateDirectory(imageBasePath);
                }
                if (!Directory.Exists(excelBasePath))
                {
                    Directory.CreateDirectory(excelBasePath);
                }
                //创建工作薄
                HSSFWorkbook workbook = new HSSFWorkbook();

                //create sheet
                HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1");
                string FileName = excelBasePath   DateTime.Now.ToString("yyyyMMddhh24mss")   ".xls";

                #region 右击文件 属性信息
                //{
                //    DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                //    dsi.Company = "http://....../";
                //    workbook.DocumentSummaryInformation = dsi;

                //    SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                //    if (HttpContext.Current.Session["realname"] != null)
                //    {
                //        si.Author = HttpContext.Current.Session["realname"].ToString();
                //    }
                //    else
                //    {
                //        if (HttpContext.Current.Session["username"] != null)
                //        {
                //            si.Author = HttpContext.Current.Session["username"].ToString();
                //        }
                //    }                                       //填加xls文件作者信息     
                //    si.ApplicationName = "NPOI";            //填加xls文件创建程序信息     
                //    si.LastAuthor = "OA系统";           //填加xls文件最后保存者信息     
                //    si.Comments = "OA系统自动创建文件";      //填加xls文件作者信息     
                //    si.Title = "ddd";               //填加xls文件标题信息     
                //    si.Subject = "ddd";              //填加文件主题信息     
                //    si.CreateDateTime = DateTime.Now;
                //    workbook.SummaryInformation = si;
                //}
                #endregion


                string strQrCodePath = "";
                //填充列标题以及样式
                int rowsNum = 0;  //行号
                HSSFRow headerRow = (HSSFRow)sheet.CreateRow(rowsNum);
                HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
                headStyle.Alignment = (HorizontalAlignment)HorizontalAlignment.Center;
                headerRow.HeightInPoints = 30;

                HSSFFont font = (HSSFFont)workbook.CreateFont();
                font.FontHeightInPoints = 13;
                font.Boldweight = 700;
                headStyle.SetFont(font);

                //headerRow.CreateCell(0, CellType.String).SetCellValue("卡二维码");
                //CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 4);
                //sheet.AddMergedRegion(cellRangeAddress);

                //headerRow.CreateCell(5, CellType.String).SetCellValue("卡号");
                //CellRangeAddress cellRangeAddress1 = new CellRangeAddress(0, 0, 5, 8);
                //sheet.AddMergedRegion(cellRangeAddress1);

                //headerRow.CreateCell(9, CellType.String).SetCellValue("密码");
                //CellRangeAddress cellRangeAddress2 = new CellRangeAddress(0, 0, 9, 12);
                //sheet.AddMergedRegion(cellRangeAddress2);


                for (int i = 0; i < 8; i  )
                {

                    if (i == 0)
                    {
                        headerRow.CreateCell(i, CellType.String).SetCellValue("维码");
                    }
                    else if (i == 2)
                    {
                        headerRow.CreateCell(i, CellType.String).SetCellValue("姓名");
                    }
                    else if (i == 3)
                    {
                        headerRow.CreateCell(i, CellType.String).SetCellValue("性别");
                    }
                    else if (i == 4)
                    {
                        headerRow.CreateCell(i, CellType.String).SetCellValue("出生时间");
                    }
                    else if (i == 5)
                    {
                        headerRow.CreateCell(i, CellType.String).SetCellValue("出生地点");
                    }
                    else
                    {
                        headerRow.CreateCell(i, CellType.String).SetCellValue("");
                    }

                }
                //合并列头单元格
                CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 2);
                sheet.AddMergedRegion(cellRangeAddress);

                //设置列的宽度
                for (int columnindex = 0; columnindex < 3; columnindex  )
                {
                    headerRow.GetCell(columnindex).CellStyle = headStyle;
                    sheet.SetColumnWidth(columnindex, 5000);
                }

                //填充数据行
                HSSFRow row = null;
                rowsNum = 1;  //行号,从第2行开始
                String j = "[{'name':'huangbiao','sex':'男','both':'','add':''},{'name':'huangbiao','sex':'男','both':'','add':''}]";
                //  string j = "{[{\"name\": \"牛顿\", \"sex\": \"男\", \"both\": \"2000\", \"add\": \"美国\"}]}";
                List<peple> list = JsonConvert.DeserializeObject<List<peple>>(j);
                foreach (peple p in list)
                {
                    //写入字段值
                    row = (HSSFRow)sheet.CreateRow(rowsNum);
                    HSSFCellStyle cellStyle = (HSSFCellStyle)workbook.CreateCellStyle();
                    cellStyle.Alignment = (HorizontalAlignment)HorizontalAlignment.Center;
                    row.HeightInPoints = 120;
                    HSSFFont cellfont = (HSSFFont)workbook.CreateFont();
                    cellfont.FontHeightInPoints = 10;
                    cellStyle.SetFont(cellfont);

                    row.CreateCell(0, CellType.String).SetCellValue("");
                    row.CreateCell(1, CellType.String).SetCellValue(p.name);
                    row.CreateCell(2, CellType.Blank).SetCellValue(p.sex);
                    row.CreateCell(3, CellType.String).SetCellValue(p.both);
                    row.CreateCell(4, CellType.Blank).SetCellValue(p.add);
                    //合并单元格
                    //CellRangeAddress rowCellRangeAddress = new CellRangeAddress(rowsNum, rowsNum, 2, 4);
                    //sheet.AddMergedRegion(rowCellRangeAddress);

                    strQrCodePath = GetQrCode(p.name);
                    byte[] bytes = System.IO.File.ReadAllBytes(strQrCodePath);
                    int pictureIdx = workbook.AddPicture(bytes, PictureType.PNG);

                    // Create the drawing patriarch.  This is the top level container for all shapes. 
                    HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();

                    //add a picture
                    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 10, 1023, 0, 0, rowsNum, 0, rowsNum);

                    HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
                    pict.Resize();

                    //设置行的高度
                    for (int rowindex = 0; rowindex < 3; rowindex  )
                    {
                        row.GetCell(rowindex).CellStyle = cellStyle;
                    }
                    rowsNum  ;
                    //删除图片文件
                    //if (File.Exists(strQrCodePath))
                    //{
                    //    File.Delete(strQrCodePath);
                    //}
                }
                //供浏览器下载Excel
                if (HttpContext.Current.Request.Browser.Browser == "IE")
                    FileName = HttpUtility.UrlEncode(FileName);
                using (MemoryStream ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                    HttpContext curContext = HttpContext.Current;

                    // 设置编码和附件格式
                    curContext.Response.ContentType = "application/vnd.ms-excel";
                    curContext.Response.ContentEncoding = Encoding.UTF8;
                    curContext.Response.Charset = "";
                    curContext.Response.AppendHeader("Content-Disposition",
                         "attachment;filename="   HttpUtility.UrlEncode(FileName, Encoding.UTF8));
                    curContext.Response.BinaryWrite(ms.GetBuffer());
                    ms.Close();
                    ms.Dispose();
                    curContext.ApplicationInstance.CompleteRequest();
                    //curContext.Response.End();
                }
            }
            catch (Exception ex)
            {
                //Page.ClientScript.RegisterStartupScript(this.GetType(), "key", "<script>alert('"   ex.Message.ToString()   "');</script>");
            }
        }

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

实例下载地址

NPOI导出excel+LAYUI+二维码的生成 实例源码

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警