NOPI导出多个sheet,一列图片

NPOI API: http://www.cnblogs.com/atao/archive/2009/11/15/1603528.html

http://blog.csdn.net/pan_junbiao/article/details/39717443 -- NPOI使用手册

http://www.cnblogs.com/wei325/p/4748324.html

每一张表只能有一个HSSFPatriarch对象,如果把它的创建放到了setPic方法中,那么一行只会出现一张图片,最后的图片会消掉之前的图片。也不能放到for循环里

HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2)的参数,有必要在这里说明一下:
dx1:起始单元格的x偏移量,如例子中的255表示直线起始位置距A1单元格左侧的距离;
dy1:起始单元格的y偏移量,如例子中的125表示直线起始位置距A1单元格上侧的距离;
dx2:终止单元格的x偏移量,如例子中的1023表示直线起始位置距C3单元格左侧的距离;
dy2:终止单元格的y偏移量,如例子中的150表示直线起始位置距C3单元格上侧的距离;
col1:起始单元格列序号,从0开始计算;
row1:起始单元格行序号,从0开始计算,如例子中col1=0,row1=0就表示起始单元格为A1;
col2:终止单元格列序号,从0开始计算;
row2:终止单元格行序号,从0开始计算,如例子中col2=2,row2=2就表示起始单元格为C3;

//添加多个图片时:多个pic应该share同一个DrawingPatriarch在同一个sheet里面。

 

        //获取枚举类型的Display特性的name值
        public string GetEnumTxt(Enum eEnum)
        {
            var enumType = eEnum.GetType();
            var field = enumType.GetField(eEnum.ToString());
            var display = field.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() as DisplayAttribute;
            return display != null ? display.Name : eEnum.ToString();
        }

        private void setPic(HSSFWorkbook workbook, HSSFPatriarch patriarch,string path, ISheet sheet, int rowline, int col)
        {
            if(string.IsNullOrEmpty(path))return;
            byte[] bytes = System.IO.File.ReadAllBytes(Server.MapPath(path));
            int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);
            // 插图片的位置  HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2) 后面再作解释
            HSSFClientAnchor anchor = new HSSFClientAnchor(70, 10, 0, 0, col, rowline, col+1, rowline + 1);
            //把图片插到相应的位置
            HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
        }

private void setPic(HSSFWorkbook workbook, HSSFPatriarch patriarch,string path, ISheet sheet, int rowline, int col)
        {
            if(string.IsNullOrEmpty(path))return;
            byte[] bytes = System.IO.File.ReadAllBytes(Server.MapPath(path));
            int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);
            // 插图片的位置  HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2) 后面再作解释
            HSSFClientAnchor anchor = new HSSFClientAnchor(70, 10, 0, 0, col, rowline, col+1, rowline + 1);
            //把图片插到相应的位置
            HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
        }

导出多个sheet,一列图片

        /// <summary>
        /// 导出EXCEL,可以导出多个sheet(图片)
        /// </summary>
        /// <param name="dtSources">sheet数据源</param>
        /// <param name="lstColname">sheet列名数据</param>
        /// <param name="sheetname">sheet名</param>
        /// <param name="filename">文件名</param>
        /// <param name="mColImage">图像列</param>
        /// <returns></returns>
        public static string ExporMultiSheetImage(List<DataTable> dtSources, List<List<string>> lstColname, List<string> sheetname, string filename,int mColImage)
        {
            //创建工作薄
            IWorkbook workbook = new HSSFWorkbook();
            string FileName = filename + ".xls";
            for (int k = 0; k < dtSources.Count; k++)
            {
                //DataTable dt = dtSources[k];
                int iSheetCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(dtSources[k].Rows.Count) / 10000));
                iSheetCount = iSheetCount == 0 ? 1 : iSheetCount;

                for (int iSheetIndex = 0; iSheetIndex < iSheetCount; iSheetIndex++)
                {
                    #region 图最大列

                    int mImageColMerage = 0;    //  图最大列
                    Dictionary<int, List<string>> dicImagePath = new Dictionary<int, List<string>>();

                    if (mColImage > -1)
                    {
                        List<int> lstImageColLen = new List<int>();

                        for (int i = iSheetIndex * 10000; i < dtSources[k].Rows.Count; i++)
                        {
                            List<string> lstImagePath = dtSources[k].Rows[i][mColImage].ToString().Trim(‘,‘).Split(new char[] { ‘,‘ }, StringSplitOptions.RemoveEmptyEntries).ToList();
                            dicImagePath[i] = lstImagePath;
                            lstImageColLen.Add(lstImagePath.Count());
                        }
                        mImageColMerage = lstImageColLen.Max();
                    }

                    #endregion

                    //create sheet
                    string sheetName = string.Empty;
                    if (iSheetCount>1)
                    {
                        sheetName = sheetname[k] + iSheetIndex;
                    }
                    else
                    {
                        sheetName = sheetname[k];
                    }
                    ISheet sheet = workbook.CreateSheet(sheetName);
                    sheet.PrintSetup.Landscape = true;     //是否横向排版
                    sheet.FitToPage = false;               //是否自适应页面
                    sheet.PrintSetup.Scale = 50;           //缩放比例

                    //填充列标题以及样式
                    int rowsNum = 0;  //行号
                    IRow headerRow = sheet.CreateRow(rowsNum);
                    ICellStyle headStyle = workbook.CreateCellStyle();
                    headStyle.Alignment = HorizontalAlignment.CENTER;
                    headerRow.HeightInPoints = 20;
                    headStyle.VerticalAlignment = VerticalAlignment.CENTER;
                    //换行
                    //headStyle.WrapText = true;

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

                    for (int i = 0; i < lstColname[k].Count; i++)
                    {
                        if (i < mColImage)
                        {
                            //合并列前
                            headerRow.CreateCell(i, CellType.STRING).SetCellValue(lstColname[k][i]);
                            headerRow.GetCell(i).CellStyle = headStyle;
                        }
                        else if (mColImage > -1 && i == mColImage)
                        {
                            headerRow.CreateCell(i, CellType.STRING).SetCellValue(lstColname[k][i]);
                            headerRow.GetCell(i).CellStyle = headStyle;
                            sheet.AddMergedRegion(new CellRangeAddress(0, 0, mColImage, mColImage + mImageColMerage));
                        }
                        else
                        {
                            //合并列后
                            headerRow.CreateCell(i + mImageColMerage, CellType.STRING).SetCellValue(lstColname[k][i]);
                            headerRow.GetCell(i + mImageColMerage).CellStyle = headStyle;
                        }
                        //sheet.AutoSizeColumn(i);
                        sheet.SetColumnWidth(i, 5000);  //列宽
                        //headerRow.Cells[i].SetCellValue(new HSSFRichTextString("\r\n"));  //强制换行
                    }

                    ICellStyle cellStyle = workbook.CreateCellStyle();
                    cellStyle.Alignment = HorizontalAlignment.CENTER;
                    cellStyle.VerticalAlignment = VerticalAlignment.CENTER;
                    IFont cellfont = workbook.CreateFont();
                    cellfont.FontHeightInPoints = 10;
                    cellStyle.SetFont(cellfont);
                    cellStyle.WrapText = true;

                    #region MyRegion

                    //填充数据行
                    IRow dataRow = null;
                    rowsNum = 1;  //行号,从第2行开始
                    /// patriarch 画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
                    HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
                    //填充内容
                    for (int i = iSheetIndex * 10000; i < dtSources[k].Rows.Count; i++)
                    {
                        dataRow = sheet.CreateRow(i + 1);

                        for (int j = 0; j < dtSources[k].Columns.Count; j++)
                        {
                            //sheet.SetColumnWidth(j, 5000);
                            //sheet.AutoSizeColumn(j);
                            if (j < mColImage)
                            {
                                //合并列前
                                dataRow.CreateCell(j).SetCellValue(dtSources[k].Rows[i][j].ToString());
                                dataRow.GetCell(j).CellStyle = cellStyle;
                            }
                            else if (mColImage > -1 && j == mColImage)
                            {
                                int mImgIndex = 0;
                                foreach (var item in dicImagePath[i])
                                {
                                    string imgPath = HttpContext.Current.Server.MapPath(item);
                                    if (File.Exists(imgPath))
                                    {
                                        byte[] bytes = System.IO.File.ReadAllBytes(imgPath);
                                        int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);
                                        ///// patriarch 画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
                                        //HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
                                        // 插图片的位置  HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2)
                                        //图片左上角为(col, row)第row+1行col+1列,右下角为( col +1, row +1)第 col +1+1行row +1+1列,宽为100,高为50
                                        HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1000, 250, mColImage + mImgIndex, i + 1, mColImage + mImgIndex, i + 1);
                                        //把图片插到相应的位置
                                        HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
                                        //pict.Resize(0.7);   //用图片原始大小来显示
                                    }
                                    mImgIndex++;
                                }
                                dataRow.CreateCell(j).SetCellValue("");
                                dataRow.GetCell(j).CellStyle = cellStyle;
                                sheet.AddMergedRegion(new CellRangeAddress(i + 1, i + 1, mColImage, mColImage + mImageColMerage));
                            }
                            else
                            {
                                //合并列后
                                dataRow.CreateCell(j + mImageColMerage).SetCellValue(dtSources[k].Rows[i][j].ToString());
                                dataRow.GetCell(j + mImageColMerage).CellStyle = cellStyle;
                            }

                        }
                    }

                    #endregion
                }
            }

            string strPhysicsPath = HttpContext.Current.Server.MapPath(Config.AccPath + "Temp/Export");

            if (!Directory.Exists(strPhysicsPath))
            {
                Directory.CreateDirectory(strPhysicsPath);
            }
            //string resultUrl = Config.LogPath.Replace("~", HttpContext.Current.Request.Url.Host + ":" + HttpContext.Current.Request.Url.Port) + "Temp/" + DateTime.Today.Year;
            string tempUrl = "/" + DateTime.Today.ToString("MMdd-") + Guid.NewGuid().ToString() + ".xls";
            strPhysicsPath = strPhysicsPath.TrimEnd(‘\\‘) + tempUrl;
            //-------
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Flush();
                ms.Position = 0;
                workbook.Write(ms);
                using (FileStream fs = new FileStream(strPhysicsPath, FileMode.Create, FileAccess.Write))
                {
                    byte[] fData = ms.ToArray();
                    fs.Write(fData, 0, fData.Length);
                    fs.Flush();
                }
                LogHelper.WriteExportLog(filename);
                return Config.AccPath.Replace("~", "") + "Temp/Export" + tempUrl;
            }

            #region  浏览器下载

            //供浏览器下载Excel
            //if (HttpContext.Current.Request.Browser.Browser == "IE")
            //    FileName = HttpUtility.UrlEncode(FileName);
            //using (MemoryStream ms = new MemoryStream())
            //{
            //    ms.Position = 0;
            //    workbook.Write(ms);
            //    ms.Flush();
            //    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.Response.End();
            //}
            #endregion
        }

导出EXCEL,可以导出多个sheet

        /// <summary>
        /// 导出EXCEL,可以导出多个sheet
        /// </summary>
        /// <param name="dtSources">原始数据数组类型</param>
        /// <param name="strFileName">路径</param>
        public static string ExporMultiSheet(DataTable[] dtSources, List<List<string>> lstname, List<string> sheetname, string filename)
        {
            //创建工作薄
            IWorkbook workbook = new HSSFWorkbook();

            string FileName = filename + ".xls";

            for (int k = 0; k < dtSources.Length; k++)
            {
                ISheet sheet = workbook.CreateSheet(sheetname[k]);
                //设置列宽
                sheet.SetColumnWidth(0, 30 * 256);
                sheet.SetColumnWidth(1, 30 * 256);
                sheet.SetColumnWidth(2, 20 * 256);
                sheet.SetColumnWidth(3, 20 * 256);
                sheet.SetColumnWidth(4, 20 * 256);
                sheet.SetColumnWidth(5, 25 * 256);
                //填充表头
                //填充列标题以及样式
                int rowsNum = 0;  //行号
                IRow headerRow = sheet.CreateRow(rowsNum);
                ICellStyle headStyle = workbook.CreateCellStyle();
                headStyle.Alignment = HorizontalAlignment.CENTER;
                headStyle.VerticalAlignment = VerticalAlignment.CENTER;
                //换行
                headStyle.WrapText = true;

                headerRow.HeightInPoints = 20;
                IFont font = workbook.CreateFont();
                font.FontHeightInPoints = 13;
                font.Boldweight = 700;
                headStyle.SetFont(font);
                for (int i = 0; i < lstname[k].Count; i++)
                {
                    headerRow.CreateCell(i, CellType.STRING).SetCellValue(lstname[k][i]);
                    headerRow.GetCell(i).CellStyle = headStyle;
                    //headerRow.Cells[i].SetCellValue(new HSSFRichTextString("\r\n"));  //强制换行
                }

                ICellStyle cellStyle = workbook.CreateCellStyle();
                cellStyle.Alignment = HorizontalAlignment.CENTER;
                cellStyle.VerticalAlignment = VerticalAlignment.CENTER;
                IFont cellfont = workbook.CreateFont();
                cellfont.FontHeightInPoints = 10;
                cellStyle.SetFont(cellfont);
                cellStyle.WrapText = true;

                //填充数据行
                IRow dataRow = null;
                rowsNum = 1;  //行号,从第2行开始  

                //填充内容
                for (int i = 0; i < dtSources[k].Rows.Count; i++)
                {
                    dataRow = sheet.CreateRow(i + 1);

                    for (int j = 0; j < dtSources[k].Columns.Count; j++)
                    {
                        dataRow.CreateCell(j).SetCellValue(dtSources[k].Rows[i][j].ToString());
                        dataRow.GetCell(j).CellStyle = cellStyle;
                    }
                }
            }

            //保存
            string strPhysicsPath = HttpContext.Current.Server.MapPath(Config.AccPath + "Temp/Export");

            if (!Directory.Exists(strPhysicsPath))
            {
                Directory.CreateDirectory(strPhysicsPath);
            }
            string tempUrl = "/" + DateTime.Today.ToString("MMdd-") + Guid.NewGuid().ToString() + ".xls";
            strPhysicsPath = strPhysicsPath.TrimEnd(‘\\‘) + tempUrl;

            using (MemoryStream ms = new MemoryStream())
            {
                ms.Flush();
                ms.Position = 0;
                workbook.Write(ms);
                using (FileStream fs = new FileStream(strPhysicsPath, FileMode.Create, FileAccess.Write))
                {
                    byte[] fData = ms.ToArray();
                    fs.Write(fData, 0, fData.Length);
                    fs.Flush();
                }
                LogHelper.WriteExportLog(filename);
                return Config.AccPath.Replace("~", "") + "Temp/Export" + tempUrl;
            }
        }

图片base64形式怎么转为图片

String u = "Base64";
            // Base64解码
            byte[] b = new BASE64Decoder().decodeBuffer(u);
            // 生成图片
            String imgName = "echartsPhoto";
            String filePath = ServletActionContext.getServletContext().getRealPath("/") + "echarts";
            String fileName = filePath +"/"+ imgName +".png";

            File file = new File(filePath);
            if(!file.exists()){
                file.mkdir();
            }
            OutputStream out = new FileOutputStream(new File(fileName));
            out.write(b);18             out.close();

时间: 2024-10-10 07:46:30

NOPI导出多个sheet,一列图片的相关文章

NOPI导出Excel

Imports System.IO Imports NPOI.HSSF.UserModel Imports NPOI.HPSF Imports NPOI.POIFS.FileSystem Imports NPOI.HSSF.Util Imports NPOI.SS.UserModel Imports NPOI.SS.Util Imports Common Public Class NopExcel Private Init_Date As String = String.Empty Privat

EPPLUS 导出excel,包括文本,图片

string[] ids = this.dDataList.SelectedIds;            if (ids.Length != 1)            {                Soyisoft.Web.WebUtil.ShowMessage(this.Page, "请选择一行数据");                return;            } string[] idArr = ids[0].Split('-');            if

代码: 两列图片瀑布流(一次后台取数据,图片懒加载。下拉后分批显示图片。图片高度未知,当图片onload后才显示容器)

代码: 两列图片瀑布流(一次后台取数据,无ajax,图片懒加载.下拉后分批显示图片.图片高度未知,当图片onload后才显示容器) [思路]: 图片瀑布流,网上代码有多种实现方式,也有各类插件.没找到合意的,所以根据网上找的一段代码,进行了较大改动. 需引用 zepto 或 jquery. 我这个是应用于手机上的,两列瀑布流,图片高度未知——等图片的onloaded事件触发后,才对容器进行计算和定位. 大容器是 $("#imgList"),容器格子是$(".pin"

Java 用Freemarker完美导出word文档(带图片)

Java  用Freemarker完美导出word文档(带图片) 前言 最近在项目中,因客户要求,将页面内容(如合同协议)导出成word,在网上翻了好多,感觉太乱了,不过最后还是较好解决了这个问题. 准备材料 1.word原件 2.编辑器(推荐Firstobject free XML editor) 实现步骤 1.用Microsoft Office Word打开word原件: 2.把需要动态修改的内容替换成***,如果有图片,尽量选择较小的图片几十K左右,并调整好位置: 3.另存为,选择保存类型

NOPI导出Excel 自定义列名

NOPI 做Excel 导出确实很方便 ,但是一直在用没好好研究. 在网上没找到自定义Columns的方法 ,于是乎自己就在原来的方法上简单地改改. 想用的童鞋们可以直接拿去用! 1 /// 数据大于65536时使用 2 /// </summary> 3 /// <param name="dt">数据源</param> 4 /// <param name="Columns">列名</param> 5 ///

NOPI 导出Excle

using System; using System.Data; using System.IO; using System.Text; using System.Web; using NPOI.HPSF; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; public class ExcelHelper { /// <summary> /// DataTable导出到Excel文件 /// </summary> /// <

Asp.net MVC 利用 Nopi 导出 Excel

/// <summary> /// 导出认账流水 /// </summary> /// <returns></returns> public ActionResult ExportAdmitBankTrans(BankTransQueryModel queryModel) { HSSFWorkbook workBook = new HSSFWorkbook(); ISheet sheet = workBook.CreateSheet("商务报表&q

NOPI导出加载模板

ListExcel导出(加载模板) 1 /// <summary> 2 /// List根据模板导出ExcelMemoryStream 3 /// </summary> 4 /// <param name="list"></param> 5 /// <param name="templdateName"></param> 6 public static MemoryStream ExportLi

npoi导出excel(模板)插入图片,文本只读,不可以修改

NPOI下载地址:http://npoi.codeplex.com/ VPurchaseOrder purchaseOrder = PurchaseDataAccess.GetPurchaseOrder(PurchaseOrderId); HSSFWorkbook hssfworkbookDown; string modelExlPath = Server.MapPath(@"\b2c\download\供应商采购单模板.xls"); FileStream file = new Fil