近期一段时间正好在做winform导出Excel报表的问题,学习了一下C#操作Excel的一些方法(如:向Excel中插入图片;删除Excel指定sheet中的某行或某列,在Excel指定的单元格中画线等)

一、加入引用
    加入com组件(Microsoft Office 11.0 Object Library )命名空间为Microsoft.Office.Interop.Excel
    加入Excel.exe引用默认路径为C:/Program Files/Microsoft Office/OFFICE11/Excel.exe

二、Excel控制类
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelOperation
{
    public class ExcelControl
    {
        private Excel.Application m_objExcel = null;
        private Excel.Workbooks m_objBooks = null;
        private Excel._Workbook m_objBook = null;
        private Excel.Sheets m_objSheets = null;
        private Excel._Worksheet m_objSheet = null;
        private Excel.Range m_objRange = null;
        private object m_objOpt = System.Reflection.Missing.Value;

/// <summary>
        /// 打开没有模板的操作。
        /// </summary>
        public void Open()
        {
            this.Open(String.Empty);
        }

/// <summary>
        /// 功能:实现Excel应用程序的打开
        /// </summary>
        /// <param name="TemplateFilePath">模板文件物理路径</param>
        public void Open(string TemplateFilePath)
        {
            //打开对象
            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;
            }

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, 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);
            }
            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);
        }

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

/// <summary>
        /// 将图片插入到指定的单元格位置。
        /// 注意:图片必须是绝对物理路径
        /// </summary>
        /// <param name="RangeName">单元格名称,比如:B4</param>
        /// <param name="PicturePath">要插入图片的绝对路径。</param>
        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);
        }

/// <summary>
        /// 将图片插入到指定的单元格位置,并设置图片的宽度和高度。
        /// 注意:图片必须是绝对物理路径
        /// </summary>
        /// <param name="RangeName">单元格名称,比如:B4</param>
        /// <param name="PicturePath">要插入图片的绝对路径。</param>
        /// <param name="PictuteWidth">插入后,图片在Excel中显示的宽度。</param>
        /// <param name="PictureHeight">插入后,图片在Excel中显示的高度。</param>
        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);
        }

/// <summary>
        /// 将图片填充到Excel中的某个或某些单元格中
        /// 注意:图片必须是绝对物理路径
        /// </summary>
        /// <param name="RangeName">单元格名称,比如:B4</param>
        /// <param name="PicturePath">要插入图片的绝对路径。</param>
        /// <param name="PictuteWidth">插入后,图片在Excel中显示的宽度。</param>
        /// <param name="PictureHeight">插入后,图片在Excel中显示的高度。</param>

/// <summary>
        /// 将图片填充到Excel中的某个或某些单元格中
        /// </summary>
        /// <param name="BeginRangeName">插入的開始单元格</param>
        /// <param name="EndRangeName">插入的结束单元格</param>
        /// <param name="PicturePath">插入图片的绝对物理路径</param>
        /// <param name="IsMergeCells">是否合并上面的单元格</param>
        public void InsertPicture(string BeginRangeName,string EndRangeName, string PicturePath,bool IsMergeCells)
        {
            m_objRange = m_objSheet.get_Range(BeginRangeName, EndRangeName);

//计算单元格的宽和高
            float PictuteWidth, PictureHeight;
            PictuteWidth = Convert.ToSingle(m_objRange.Width);
            PictureHeight = Convert.ToSingle(m_objRange.Height);

if (IsMergeCells)
            {
                //合并单元格
                m_objRange.Merge(System.Reflection.Missing.Value);
                m_objRange = m_objSheet.get_Range(BeginRangeName, BeginRangeName);
            }
            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);
        }

/// <summary>
        /// 
        /// </summary>
        /// <param name="BeginRangeName"></param>
        /// <param name="EndRangeName"></param>
        /// <param name="IsMergeCells"></param>
        public void InsertLine(string BeginRangeName, string EndRangeName, bool IsMergeCells)
        {
            m_objRange = m_objSheet.get_Range(BeginRangeName, EndRangeName);

//计算单元格的宽和高
            float PictureWidth, PictureHeight;
            PictureWidth = Convert.ToSingle(m_objRange.Width);
            PictureHeight = Convert.ToSingle(m_objRange.Height);

if (IsMergeCells)
            {
                //合并单元格
                m_objRange.Merge(System.Reflection.Missing.Value);
                m_objRange = m_objSheet.get_Range(BeginRangeName, BeginRangeName);
            }
            m_objRange.Select();
            float PicLeft, PicTop;
            PicLeft = Convert.ToSingle(m_objRange.Left);
            PicTop = Convert.ToSingle(m_objRange.Top);
            //參数含义:
            //线的起点(X,Y)
            //线的终点(X,Y)
            m_objSheet.Shapes.AddLine(PicLeft,PicTop,PicLeft + PictureWidth,PicTop +PictureHeight); 
        }

/// <summary>
        /// 将Excel文件保存到指定的文件夹,文件夹必须事先存在,文件名不一定要存在。
        /// </summary>
        /// <param name="OutputFilePath">要保存成的文件的全路径。</param>
        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();
        }
        /// <summary>
        /// 关闭应用程序
        /// </summary>
        private void Close()
        {
            m_objBook.Close(false, m_objOpt, m_objOpt);
            m_objExcel.Quit();
        }

/// <summary>
        /// 释放所引用的COM对象。注意:这个过程一定要运行。
        /// </summary>
        public void Dispose()
        {
            ReleaseObj(m_objSheets);
            ReleaseObj(m_objBook);
            ReleaseObj(m_objBooks);
            ReleaseObj(m_objExcel);
            System.GC.Collect();
            System.GC.WaitForPendingFinalizers();
        }
        /// <summary>
        /// 释放对象,内部调用
        /// </summary>
        /// <param name="o"></param>
        private void ReleaseObj(object o)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
            }
            catch { }
            finally { o = null; }
        }

/// <summary>
        /// 删除指定sheet下的指定行
        /// </summary>
        /// <param name="SheetIndex">sheet索引</param>
        /// <param name="DeleteRowIndex">行索引</param>
        public void DeleteRow(int SheetIndex, int DeleteRowIndex)
        {
            m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(SheetIndex));
            m_objRange = (Excel.Range)m_objSheet.Rows[DeleteRowIndex, System.Reflection.Missing.Value];
            m_objRange.EntireRow.Delete(Excel.XlDirection.xlToRight);
        }

/// <summary>
        /// 删除指定sheet下的指定列
        /// </summary>
        /// <param name="SheetIndex">sheet索引</param>
        /// <param name="DeleteColumnIndex">列索引</param>
        public void DeleteColumn(int SheetIndex, int DeleteColumnIndex)
        {
            m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(SheetIndex));
            m_objRange = (Excel.Range)m_objSheet.Columns[DeleteColumnIndex, System.Reflection.Missing.Value];
            m_objRange.EntireColumn.Delete(Excel.XlDirection.xlDown);
        }
    }
}

三、Excel操作方法调用
1.插入图片和线调用
            PictureInExcel ipt = new PictureInExcel();
            ipt.Open();
            //ipt.InsertPicture("B2", @"C:/www.jpg");
            //ipt.InsertPicture("B8", @"C:/www.jpg", 1000, 800);
            ipt.InsertPicture("B2","F8", @"C:/www.jpg",true);
            ipt.InsertLine("B9", "F15", true);
            ipt.InsertPicture("B16", "F22", @"C:/www.jpg", false);
            ipt.InsertLine("B23", "F29", false);
            ipt.SaveFile(@"C:/ExcelTest.xls");
            ipt.Dispose();

2.删除行方法调用
            PictureInExcel ipt = new PictureInExcel();
            ipt.Open(@"C:/ExcelTest.xls");
            ipt.DeleteRow(1,1);
            ipt.SaveFile(@"C:/ExcelTest.xls");
            ipt.Dispose();

3.删除列方法调用
            PictureInExcel ipt = new PictureInExcel();
            ipt.Open(@"C:/ExcelTest.xls");
            ipt.DeleteColumn(1, 1);
            ipt.SaveFile(@"C:/ExcelTest.xls");
            ipt.Dispose();

四、參考资料
    孟子E章的 《C#向Excel报表中插入图片的2种方法》等

[转]C#操作Excel初探的更多相关文章

  1. C#操作Excel初探

        近期一段时间正好在做winform导出Excel报表的问题,学习了一下C#操作Excel的一些方法(如:向Excel中插入图片:删除Excel指定sheet中的某行或某列,在Excel指定的单 ...

  2. 免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)

    很多的软件项目几乎都包含着对文档的操作,前面已经介绍过两款操作文档的组件,现在介绍一款文档操作的组件NPOI. NPOI可以生成没有安装在您的服务器上的Microsoft Office套件的Excel ...

  3. C#通过NPOI操作Excel

    参考页面: http://www.yuanjiaocheng.net/webapi/create-crud-api-1-post.html http://www.yuanjiaocheng.net/w ...

  4. POI操作Excel

    POI和Excel简介 JAVA中操作Excel的有两种比较主流的工具包: JXL 和 POI .jxl 只能操作Excel 95, 97, 2000也即以.xls为后缀的excel.而poi可以操作 ...

  5. NPOI操作EXCEL(六)——矩阵类表头EXCEL模板的解析

    哈哈~~~很高兴还活着.总算加班加点的把最后一类EXCEL模板的解析做完了... 前面几篇文章介绍了博主最近项目中对于复杂excel表头的解析,写得不好,感谢园友们的支持~~~ 今天再简单讲诉一下另一 ...

  6. VB操作EXCEL文件

    用VB操作Excel(VB6.0)(整理) 首先创建Excel对象,使用ComObj:Dim ExcelID as Excel.ApplicationSet ExcelID as new Excel. ...

  7. VB.NET操作Excel

    VB.NET操作Excel的基本方法与例子:

  8. C# 操作excel单元格居中

    C# 操作excel //导出Excel        private void ExportExcel(string fileName, System.Data.DataTable myDGV, s ...

  9. NPOI操作Excel辅助类

    /// <summary> /// NPOI操作excel辅助类 /// </summary> public static class NPOIHelper { #region ...

随机推荐

  1. Vue.js - 路由 vue-router 的使用详解2(参数传递)

    一.使用冒号(:)的形式传递参数 1,路由列表的参数设置 (1)路由列表的 path 是可以带参数的,我们在路由配置文件(router/index.js)里以冒号的形式设置参数. (2)下面样例代码中 ...

  2. java排序算法之冒泡排序和快速排序

    总结一下Java排序算法,以便记忆. 各类排序的时间复杂度: 排序方法 时间复杂度(平均) 时间复杂度(最坏) 时间复杂度(最好) 空间复杂度 稳定性 复杂性 直接插入排序 O(n2)O(n2) O( ...

  3. PAT_A1090#Highest Price in Supply Chain

    Source: PAT A1090 Highest Price in Supply Chain (25 分) Description: A supply chain is a network of r ...

  4. 20140408 父类指针指向子类对象 ;delete ;static作用

    1.父类指针可以指向子类对象 静态联翩:如果以父类指针指向派生类对象,那么经由该指针只能访问父类定义的函数 动态联编:根据指针实际指向的对象类型确定 2.面试宝典 P110 面试题5  #includ ...

  5. 8张图带你轻松温习Java知识

    年初四好,一图胜千言,下面图解均来自Program Creek 网站,目前它们拥有最多的票选. 如果图解没有阐明问题,那么你可以借助它的标题来一窥究竟. 1 字符串不变性 下面这张图展示了这段代码做了 ...

  6. Spring Boot 文件下载

    1. 文件下载类 import javax.servlet.http.HttpServletResponse; import java.io.*; public class DownloadUtil ...

  7. sort()和优先队列的总结

    一.关于sort函数 sort()排序函数默认是从小到大, a={5,3,2,1,6 }; sort(a,a+n); //输出是1 2 3 5 6 ​这里如果要从到小排序,则有两种方式可以满足 (1) ...

  8. 007-Java可变个数形参重载【数组和...】

    重载方法时,可变个数形参的方法有两种方式 数组重载 ...重载 对两种方法,其实是一致的,示例如下: public class MethodArgsTest { //可变个数形参的格式:数据类型... ...

  9. 修改jupyter保存文件目录

    参考: https://blog.csdn.net/lyxuefeng/article/details/79469189 步骤 打开 cmd 输入命令 jupyter notebook --gener ...

  10. 调整VMware中虚拟机中Linux系统屏幕分辨率的问题

    即:解决显示底部菜单栏以及安装软件中没有下一步的按钮用Tab键的问题 右击打开终端,输入以下命令: Xrandr Xrandr -s  1280x720 (自己选择一个分辨率即可) 原文:https: ...