asp.net两种方式在模板excel中插入图片:npoi和c# com组件

1.npoi

看具体方法代码:

public void WorkFlowDAC1(string FileName,string xpath)
        {
            try
            {
                //InitializeWorkbook();
                string path =  FileName + ".xls";
                FileStream fs = new FileStream(xpath+"//"+path, FileMode.Open,FileAccess.Read);
                HSSFWorkbook hssfworkbook = new HSSFWorkbook(fs);

                HSSFSheet sheet1 = (HSSFSheet)hssfworkbook.GetSheet("sheet1");
                //Sheet sheet1 = hssfworkbook.GetSheet("sheet1");

                HSSFPatriarch patriarch = (HSSFPatriarch)sheet1.DrawingPatriarch;
                //create the anchor
                HSSFClientAnchor anchor;
                anchor = new HSSFClientAnchor(0, 0, 0, 255, 2, 2, 4, 7);
                //anchor.AnchorType = 2;
                //load the picture and get the picture index in the workbook
                HSSFPicture picture = (HSSFPicture)patriarch.CreatePicture(anchor, LoadImage(xpath+"//"+FileName+".jpg", hssfworkbook));
                //Reset the image to the original size.
                //picture.Resize();
                //picture.LineStyle = HSSFPicture.LINESTYLE_DASHDOTGEL;
                ///hssfworkbook.
               FileStream file = new FileStream(xpath + @"//"+FileName+@".xls", FileMode.Create);
                hssfworkbook.Write(file);
                fs.Close();
                file.Close();
               
            }
            catch(Exception ee)
            {
                FileName = "";
            }
        }

        public static int LoadImage(string path, HSSFWorkbook wb)
        {
            FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[file.Length];
            file.Read(buffer, 0, (int)file.Length);
            return wb.AddPicture(buffer, PictureType.JPEG);

        }

 

以上代码已经很详细了,请自己研究,有问题欢迎讨论

 

2、c#代码

主要是孟子的代码

 

基础类代码:

 

using System;
using System.Collections.Generic;
using System.Web;
using Excel = Microsoft.Office.Interop.Excel;

namespace ContractBarcode
{
    public class InsertPictureToExcel
    {
        ///


        /// 打开没有模板的操作。
        ///

        public void Open()
        {
            this.Open(String.Empty);
        }

        ///


        /// 功能:实现Excel应用程序的打开
        ///

        /// 模板文件物理路径
        public void Open(string TemplateFilePath)
        {
            //得到WorkBook对象, 下面的是打开已有的文件 

 

            //打开对象
            m_objExcel = new Excel.Application();
            m_objExcel.Visible = false;
            m_objExcel.DisplayAlerts = false;

            //if (m_objExcel.Version != "11.0")
            //{
            // // MessageBox.Show("您的 Excel 版本不是 11.0 (Office 2003),操作可能会出现问题。");
            //  m_objExcel.Quit();
            //  return;
            //}
            //Excel.Workbook xBook = m_objExcel.Workbooks._Open(@"D:/test.xls", m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);

            ////指定要操作的Sheet,两种方式: 
            //Excel.Worksheet xSheet = (Excel.Worksheet)xBook.Sheets[1];
            m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;
            if (TemplateFilePath.Equals(String.Empty))
            {
                m_objBook = (Excel._Workbook)(m_objBooks.Add(m_objOpt));
            }
            else
            {
                m_objBook = m_objBooks.Open(TemplateFilePath, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
            }
            m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
            m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));
            m_objExcel.WorkbookBeforeClose += new Excel.AppEvents_WorkbookBeforeCloseEventHandler(m_objExcel_WorkbookBeforeClose);
        }

        public void m_objExcel_WorkbookBeforeClose(Excel.Workbook m_objBooks, ref bool _Cancel)
        {
            // MessageBox.Show("保存完毕!");
        }

        ///


        /// 将图片插入到指定的单元格位置。
        /// 注意:图片必须是绝对物理路径
        ///

        /// 单元格名称,例如:B4
        /// 要插入图片的绝对路径。
        public void InsertPicture(string RangeName, string PicturePath)
        {
            m_objRange = m_objSheet.get_Range(RangeName, m_objOpt);
            m_objRange.Select();
            Excel.Pictures pics = (Excel.Pictures)m_objSheet.Pictures(m_objOpt);
            pics.Insert(PicturePath, m_objOpt);
        }

        ///


        /// 将图片插入到指定的单元格位置,并设置图片的宽度和高度。
        /// 注意:图片必须是绝对物理路径
        ///

        /// 单元格名称,例如:B4
        /// 要插入图片的绝对路径。
        /// 插入后,图片在Excel中显示的宽度。
        /// 插入后,图片在Excel中显示的高度。
        public void InsertPicture(string RangeName, string PicturePath, float PictuteWidth, float PictureHeight)
        {
            m_objRange = m_objSheet.get_Range(RangeName, m_objOpt);
            m_objRange.Select();
            float PicLeft, PicTop;
            PicLeft = Convert.ToSingle(m_objRange.Left);
            PicTop = Convert.ToSingle(m_objRange.Top);
            //参数含义:
            //图片路径
            //是否链接到文件
            //图片插入时是否随文档一起保存
            //图片在文档中的坐标位置(单位:points)
            //图片显示的宽度和高度(单位:points)
            //参数详细信息参见:http://msdn2.microsoft.com/zh-cn/library/aa221765(office.11).aspx
            m_objSheet.Shapes.AddPicture(PicturePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, PicLeft, PicTop, PictuteWidth, PictureHeight);
        }

        ///


        /// 将Excel文件保存到指定的目录,目录必须事先存在,文件名称不一定要存在。
        ///

        /// 要保存成的文件的全路径。
        public void SaveFile(string OutputFilePath)
        {
            m_objBook.SaveAs(OutputFilePath, m_objOpt, m_objOpt,
              m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange,
              m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);

            this.Close();
        }
        ///


        /// 关闭应用程序
        ///

        public void Close()
        {
            m_objBook.Close(false, m_objOpt, m_objOpt);
            m_objExcel.Quit();
        }

        ///


        /// 释放所引用的COM对象。注意:这个过程一定要执行。
        ///

        public void Dispose()
        {
            ReleaseObj(m_objSheets);
            ReleaseObj(m_objBook);
            ReleaseObj(m_objBooks);
            ReleaseObj(m_objExcel);
            System.GC.Collect();
            System.GC.WaitForPendingFinalizers();
        }
        ///
        /// 释放对象,内部调用
        ///

        ///
        public void ReleaseObj(object o)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
            }
            catch { }
            finally { o = null; }
        }

        public Excel.Application m_objExcel = null;
        public Excel.Workbooks m_objBooks = null;
        public Excel._Workbook m_objBook = null;
        public Excel.Sheets m_objSheets = null;
        public Excel._Worksheet m_objSheet = null;
        public Excel.Range m_objRange = null;
        public object m_objOpt = System.Reflection.Missing.Value;
    }
}

 

执行代码:

 

public void addPic(string fielname,string path)
        {
            ContractBarcode.InsertPictureToExcel ipt = new ContractBarcode.InsertPictureToExcel();
            ipt.Open(path+fielname+".xls");
            ipt.InsertPicture("B2", path + fielname + ".jpg");
            //ipt.InsertPicture("i8", @"C:/1.jpg", 120, 80);
            ipt.SaveFile(path + fielname + ".xls");
            ipt.Dispose();
        }

 

 

 

NPOI的方法,如果模板中有图片的话,原有的图片会消失掉,不知道什么原因,到现在还未解决,优点是方便,快捷。

你可能感兴趣的:(asp.net两种方式在模板excel中插入图片:npoi和c# com组件)