NPOI 導出excel帶圖片,可控大小


using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.DDF;
using NPOI.SS.UserModel;
using System.IO;
using NPOI.SS;  
#region 導出
        protected void btnexcel_Click(object sender, EventArgs e)
        {
            QQT_BLL.gg_content bll = new QQT_BLL.gg_content();
            DataSet ds = bll.getds("");
            DataTable dt = ds.Tables[0];
            string excelname = System.DateTime.Now.ToString().Replace(":", "").Replace("-", "").Replace(" ", "");
            string filePath = System.Web.HttpContext.Current.Server.MapPath("ReadExcel") + "\\" + excelname + ".xls";
            MemoryStream ms = RenderDataTableToExcel(dt) as MemoryStream;
            FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
            byte[] data = ms.ToArray();
            fs.Write(data, 0, data.Length);
            fs.Flush();
            fs.Close();
            data = null;
            ms = null;
            fs = null;

            #region 導出到客戶端
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.AppendHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(excelname, System.Text.Encoding.UTF8) + ".xls");
            Response.ContentType = "Application/excel";
            Response.WriteFile(filePath);
            Response.End();
            #endregion
        }
        public Stream RenderDataTableToExcel(DataTable SourceTable)
        {
         
            MemoryStream ms = new MemoryStream();
            NPOI.HSSF.UserModel.HSSFWorkbook workbook = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet();
            NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow(0);

          //設置7列寬為100
            sheet.SetColumnWidth(7, 100);
         //加標題

            headerRow.CreateCell(0).SetCellValue("廣告編號");
            headerRow.CreateCell(1).SetCellValue("廣告標題");
            headerRow.CreateCell(2).SetCellValue("廣告內容");
            headerRow.CreateCell(3).SetCellValue("所屬廣告商");
            headerRow.CreateCell(4).SetCellValue("廣告電話");
            headerRow.CreateCell(5).SetCellValue("廣告網址");
            headerRow.CreateCell(6).SetCellValue("廣告小圖片");
            headerRow.CreateCell(7).SetCellValue("圖片顯示");
            headerRow.CreateCell(8).SetCellValue("廣告大圖片");
            headerRow.CreateCell(9).SetCellValue("圖片顯示");
            headerRow.CreateCell(10).SetCellValue("審核狀態");

            int rowIndex = 1;
            foreach (DataRow row in SourceTable.Rows)
            {
                NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(rowIndex);
                dataRow.Height = 50;

               //列高50
                
                dataRow.CreateCell(0).SetCellValue(row["gg_id"].ToString());
                dataRow.CreateCell(1).SetCellValue(row["gg_title"].ToString());
                dataRow.CreateCell(2).SetCellValue(row["gg_memo"].ToString());
                dataRow.CreateCell(3).SetCellValue(row["ggs_name"].ToString());
                dataRow.CreateCell(4).SetCellValue(row["gg_tel"].ToString());
                dataRow.CreateCell(5).SetCellValue(row["gg_add"].ToString());
                dataRow.CreateCell(6).SetCellValue(row["p_name"].ToString());
                string picurl = row["p_url"].ToString();  //圖片存儲路徑             
                dataRow.CreateCell(8).SetCellValue(row["gg_check"].ToString());
                AddPieChart(sheet,  workbook, picurl,rowIndex ,7);
                rowIndex++;
            }
            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;
            sheet = null;
            headerRow = null;
            workbook = null;
            return ms;
        }
      
        ///
        /// 向sheet插入圖片
        ///
        ///
        ///
        private void AddPieChart(ISheet sheet,   HSSFWorkbook  workbook, string fileurl,int row,int col)
        {
            try
            {
                //add picture data to this workbook.
                string path = Server.MapPath("~/html/");
                if (fileurl.Contains("/"))
                {
                    path += fileurl.Substring( fileurl.IndexOf ('/'));
                }
                string FileName = path;
                byte[] bytes = System.IO.File.ReadAllBytes(FileName);

                if (!string.IsNullOrEmpty(FileName))
                {
                    int pictureIdx = workbook.AddPicture(bytes,NPOI .SS .UserModel .PictureType.JPEG);                  
                    HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
                    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 100, 50, col , row , col +1, row +1);
                    //##處理照片位置,【圖片左上角為(col, row)第row+1行col+1列,右下角為( col +1, row +1)第 col +1+1行row +1+1列,寬為100,高為50

                    HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
                
                   // pict.Resize();這句話一定不要,這是用圖片原始大小來顯示
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM