NPOI 导出数据到Excel(包括图片)

来源:互联网 发布:mac rvm装ruby 失败 编辑:程序博客网 时间:2024/05/21 10:55

   RT,对于asp.net导出页面数据到Excel,图片一直是个问题,这里我把我的处理方法分享给大家,用第三方组件NPOI来实现,同时玩玩二维码生成。

首先,新建一个webApplication,添加NPOI引用,这里还要添加一个二维码的dll

下载地址:点击打开链接


添加引用之后,新建一个aspx页面,我取名为QrEncoderPage.aspx

前台页面html源码如下:

[html] view plaincopy
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="QrEncoderPage.aspx.cs"  
  2.     Inherits="WebQrCodeNet.QrEncoderPage" %>  
  3.   
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.         <asp:GridView ID="gvCardList" runat="server" Width="100%" AutoGenerateColumns="False"  
  13.             RowStyle-CssClass="DataAlign" OnRowCommand="gvCardList_RowCommand" Style="margin-top: 15px">  
  14.             <Columns>  
  15.                 <asp:BoundField DataField="CardCode" HeaderText="卡号" SortExpression="CardCode" ReadOnly="True"  
  16.                     ControlStyle-CssClass="text">  
  17.                     <ControlStyle CssClass="text"></ControlStyle>  
  18.                     <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />  
  19.                 </asp:BoundField>  
  20.                 <asp:BoundField DataField="Password" HeaderText="密码" SortExpression="Password" ReadOnly="True"  
  21.                     ControlStyle-CssClass="text">  
  22.                     <ControlStyle CssClass="text"></ControlStyle>  
  23.                     <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />  
  24.                 </asp:BoundField>  
  25.                 <asp:TemplateField ShowHeader="False">  
  26.                     <ItemTemplate>  
  27.                         <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandArgument='<%# Eval("CardCode") %>'  
  28.                             Text="选择"></asp:LinkButton>  
  29.                     </ItemTemplate>  
  30.                 </asp:TemplateField>  
  31.             </Columns>  
  32.             <RowStyle CssClass="GridViewRowStyle" />  
  33.             <SelectedRowStyle CssClass="GridViewSelectedRowStyle" />  
  34.             <PagerTemplate>  
  35.             </PagerTemplate>  
  36.             <AlternatingRowStyle CssClass="GridViewAlternatingRowStyle" />  
  37.             <HeaderStyle CssClass="GridViewHeaderStyle" />  
  38.         </asp:GridView>  
  39.     </div>  
  40.     <div>  
  41.         <%-- 输入QR code内容:  
  42.         <asp:TextBox ID="txtContent" runat="server"></asp:TextBox>--%>  
  43.         <asp:Button ID="btnGenerateCode" runat="server" Text="生成二维码" OnClick="btnGenerateCode_Click" />  
  44.     </div>  
  45.     </form>  
  46. </body>  
  47. </html>  

接着,解释后台代码,很简单,我就不解释了,大家应该看的懂,


[csharp] view plaincopy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using Gma.QrCodeNet.Encoding;  
  8. using System.IO;  
  9. using System.Drawing.Imaging;  
  10. using System.Drawing;  
  11. using NPOI;  
  12. using NPOI.HSSF.UserModel;  
  13. using Gma.QrCodeNet.Encoding.Windows.Render;  
  14. using NPOI.SS.UserModel;  
  15. using System.Text;  
  16. using NPOI.SS.Util;  
  17. using System.Collections;  
  18. using System.Text.RegularExpressions;  
  19. using NPOI.HPSF;  
  20.   
  21. namespace WebQrCodeNet  
  22. {  
  23.     public partial class QrEncoderPage : System.Web.UI.Page  
  24.     {  
  25.         private static readonly string imageBasePath = "D:\\PathConfig\\";  
  26.         private static readonly string excelBasePath = "D:\\PathConfig\\";  
  27.         protected void Page_Load(object sender, EventArgs e)  
  28.         {  
  29.             if (!IsPostBack)  
  30.             {  
  31.                 Bind();  
  32.             }  
  33.         }  
  34.   
  35.         protected void Bind()  
  36.         {  
  37.             //string jsonobjstr = HttpHelper.QueryString("json", "");  
  38.             List<PrintCard> cards = new List<PrintCard>()   
  39.             {  
  40.                 new PrintCard{ CardCode="0230010900010336",Password= "123456"},  
  41.                 new PrintCard{ CardCode="0230010900010339",Password="123456"},  
  42.                 new PrintCard{ CardCode="0230010900010340",Password= "123456"},  
  43.                 new PrintCard{ CardCode="0230000900010340",Password= "123456"},  
  44.                 new PrintCard{ CardCode="0230020900010349",Password="123456"}  
  45.             };  
  46.             try  
  47.             {  
  48.                 // cards = JsonHelper.JsonDeserialize<List<Card>>(jsonobjstr);  
  49.                 Session["ListPrintCard"] = cards;  
  50.   
  51.                 gvCardList.DataSource = cards;  
  52.                 gvCardList.DataBind();  
  53.             }  
  54.             catch (Exception ex)  
  55.             {  
  56.                 Page.ClientScript.RegisterStartupScript(this.GetType(), "key""<script>alert('" + ex.Message.ToString() + "');</script>");  
  57.                 return;  
  58.             }  
  59.         }  
  60.         public class PrintCard  
  61.         {  
  62.             public string CardCode { getset; }  
  63.             public string Password { getset; }  
  64.         }  
  65.         /// <summary>  
  66.         /// 生成二维码  
  67.         /// </summary>  
  68.         /// <param name="QrCodeStr">二维码字符串</param>  
  69.         /// <returns></returns>  
  70.         public string GetQrCode(string QrCodeStr)  
  71.         {  
  72.             string FileName = imageBasePath + Guid.NewGuid().ToString() + ".png";  
  73.             try  
  74.             {  
  75.                 QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.L);  
  76.                 QrCode qrCode = new QrCode();  
  77.                 qrEncoder.TryEncode(QrCodeStr, out qrCode);  
  78.                 GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);  
  79.                 using (FileStream stream = new FileStream(FileName, FileMode.Create))  
  80.                 {  
  81.                     renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);  
  82.                 }  
  83.             }  
  84.             catch (Exception ex)  
  85.             {  
  86.                 FileName = "";  
  87.                 throw ex;  
  88.             }  
  89.             return FileName;  
  90.         }  
  91.   
  92.   
  93.         protected void btnGenerateCode_Click(object sender, EventArgs e)  
  94.         {  
  95.             //GenerateQrCodeNet();  
  96.             AddPicture();  
  97.         }  
  98.         /// <summary>  
  99.         /// 二维码导出到Excel  
  100.         /// </summary>  
  101.         protected void AddPicture()  
  102.         {  
  103.             try  
  104.             {  
  105.                 if (!Directory.Exists(imageBasePath))  
  106.                 {  
  107.                     Directory.CreateDirectory(imageBasePath);  
  108.                 }  
  109.                 if (!Directory.Exists(excelBasePath))  
  110.                 {  
  111.                     Directory.CreateDirectory(excelBasePath);  
  112.                 }  
  113.                 //创建工作薄  
  114.                 HSSFWorkbook workbook = new HSSFWorkbook();  
  115.   
  116.                 //create sheet  
  117.                 HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1");  
  118.                 string FileName = excelBasePath + DateTime.Now.ToString("yyyyMMddhh24mss") + ".xls";  
  119.  
  120.                 #region 右击文件 属性信息  
  121.                 //{  
  122.                 //    DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();  
  123.                 //    dsi.Company = "http://....../";  
  124.                 //    workbook.DocumentSummaryInformation = dsi;  
  125.   
  126.                 //    SummaryInformation si = PropertySetFactory.CreateSummaryInformation();  
  127.                 //    if (HttpContext.Current.Session["realname"] != null)  
  128.                 //    {  
  129.                 //        si.Author = HttpContext.Current.Session["realname"].ToString();  
  130.                 //    }  
  131.                 //    else  
  132.                 //    {  
  133.                 //        if (HttpContext.Current.Session["username"] != null)  
  134.                 //        {  
  135.                 //            si.Author = HttpContext.Current.Session["username"].ToString();  
  136.                 //        }  
  137.                 //    }                                       //填加xls文件作者信息       
  138.                 //    si.ApplicationName = "NPOI";            //填加xls文件创建程序信息       
  139.                 //    si.LastAuthor = "OA系统";           //填加xls文件最后保存者信息       
  140.                 //    si.Comments = "OA系统自动创建文件";      //填加xls文件作者信息       
  141.                 //    si.Title = "ddd";               //填加xls文件标题信息       
  142.                 //    si.Subject = "ddd";              //填加文件主题信息       
  143.                 //    si.CreateDateTime = DateTime.Now;  
  144.                 //    workbook.SummaryInformation = si;  
  145.                 //}  
  146.                 #endregion  
  147.   
  148.   
  149.                 string strQrCodePath = "";  
  150.                 //填充列标题以及样式  
  151.                 int rowsNum = 0;  //行号  
  152.                 HSSFRow headerRow = (HSSFRow)sheet.CreateRow(rowsNum);  
  153.                 HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();  
  154.                 headStyle.Alignment = (HorizontalAlignment)HorizontalAlignment.CENTER;  
  155.                 headerRow.HeightInPoints = 30;  
  156.   
  157.                 HSSFFont font = (HSSFFont)workbook.CreateFont();  
  158.                 font.FontHeightInPoints = 13;  
  159.                 font.Boldweight = 700;  
  160.                 headStyle.SetFont(font);  
  161.   
  162.                 headerRow.CreateCell(0, CellType.STRING).SetCellValue("卡号");  
  163.                 headerRow.CreateCell(1, CellType.STRING).SetCellValue("密码");  
  164.                 headerRow.CreateCell(2, CellType.STRING).SetCellValue("卡二维码");  
  165.                 //合并列头单元格  
  166.                 //CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 2, 4);  
  167.                 //sheet.AddMergedRegion(cellRangeAddress);  
  168.   
  169.                 //设置列的宽度  
  170.                 for (int columnindex = 0; columnindex < 3; columnindex++)  
  171.                 {  
  172.                     headerRow.GetCell(columnindex).CellStyle = headStyle;  
  173.                     sheet.SetColumnWidth(columnindex, 5000);  
  174.                 }  
  175.   
  176.                 //填充数据行  
  177.                 HSSFRow row = null;  
  178.                 rowsNum = 1;  //行号,从第2行开始  
  179.                 List<PrintCard> list = (List<PrintCard>)Session["ListPrintCard"];  
  180.                 foreach (PrintCard p in list)  
  181.                 {  
  182.                     //写入字段值  
  183.                     row = (HSSFRow)sheet.CreateRow(rowsNum);  
  184.                     HSSFCellStyle cellStyle = (HSSFCellStyle)workbook.CreateCellStyle();  
  185.                     cellStyle.Alignment = (HorizontalAlignment)HorizontalAlignment.CENTER;  
  186.                     row.HeightInPoints = 120;  
  187.                     HSSFFont cellfont = (HSSFFont)workbook.CreateFont();  
  188.                     cellfont.FontHeightInPoints = 10;  
  189.                     cellStyle.SetFont(cellfont);  
  190.   
  191.                     row.CreateCell(0, CellType.STRING).SetCellValue(p.CardCode);  
  192.                     row.CreateCell(1, CellType.STRING).SetCellValue(p.Password);  
  193.                     row.CreateCell(2, CellType.BLANK).SetCellValue("");  
  194.   
  195.                     //合并单元格  
  196.                     //CellRangeAddress rowCellRangeAddress = new CellRangeAddress(rowsNum, rowsNum, 2, 4);  
  197.                     //sheet.AddMergedRegion(rowCellRangeAddress);  
  198.   
  199.                     strQrCodePath = GetQrCode(p.CardCode);  
  200.                     byte[] bytes = System.IO.File.ReadAllBytes(strQrCodePath);  
  201.                     int pictureIdx = workbook.AddPicture(bytes, PictureType.PNG);  
  202.   
  203.                     // Create the drawing patriarch.  This is the top level container for all shapes.   
  204.                     HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();  
  205.   
  206.                     //add a picture  
  207.                     HSSFClientAnchor anchor = new HSSFClientAnchor(0, 10, 1023, 0, 2, rowsNum, 2, rowsNum);  
  208.   
  209.                     HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);  
  210.                     pict.Resize();  
  211.   
  212.                     //设置行的高度  
  213.                     for (int rowindex = 0; rowindex < 3; rowindex++)  
  214.                     {  
  215.                         row.GetCell(rowindex).CellStyle = cellStyle;  
  216.                     }  
  217.                     rowsNum++;  
  218.                     //删除图片文件  
  219.                     if (File.Exists(strQrCodePath))  
  220.                     {  
  221.                         File.Delete(strQrCodePath);  
  222.                     }  
  223.                 }  
  224.                 //供浏览器下载Excel  
  225.                 if (HttpContext.Current.Request.Browser.Browser == "IE")  
  226.                     FileName = HttpUtility.UrlEncode(FileName);  
  227.                 using (MemoryStream ms = new MemoryStream())  
  228.                 {  
  229.                     workbook.Write(ms);  
  230.                     ms.Flush();  
  231.                     ms.Position = 0;  
  232.                     HttpContext curContext = HttpContext.Current;  
  233.   
  234.                     // 设置编码和附件格式  
  235.                     curContext.Response.ContentType = "application/vnd.ms-excel";  
  236.                     curContext.Response.ContentEncoding = Encoding.UTF8;  
  237.                     curContext.Response.Charset = "";  
  238.                     curContext.Response.AppendHeader("Content-Disposition",  
  239.                          "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8));  
  240.                     curContext.Response.BinaryWrite(ms.GetBuffer());  
  241.                     ms.Close();  
  242.                     ms.Dispose();  
  243.                     curContext.Response.End();  
  244.                 }  
  245.             }  
  246.             catch (Exception ex)  
  247.             {  
  248.                 Page.ClientScript.RegisterStartupScript(this.GetType(), "key""<script>alert('" + ex.Message.ToString() + "');</script>");  
  249.             }  
  250.   
  251.   
  252.   
  253.         }  
  254.   
  255.         protected void gvCardList_RowCommand(object sender, GridViewCommandEventArgs e)  
  256.         {  
  257.             string cardCode = e.CommandArgument.ToString();  
  258.   
  259.         }  
  260.     }  
  261. }  
0 0
原创粉丝点击