Visual Studio 进行Excel相关开发,Microsoft.Office.Interop.Excel.dll库

1、 Interop.Excel.dll 的查找

本文中将 Microsoft.Office.Interop.Excel.dll库简称为Interop.Excel.dll库

其实在使用Visual Studio进行Office的Excel开发时,Microsoft.Office.Interop.Excel.dll 可以在类似于下面的目录中找到。并不需要再在网上下载了。

E:\Program Files\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\PIA\Office14

2、Interop.Excel.dll 中类的介绍

ApplicationClass

就是我们的excel应用程序

Workbook

就是我们平常见的一个个excel文件,经常是使用Workbooks类对其进行操作。

Worksheet

excel文件中的一个个sheet页。

Worksheet.Cells[row, column]

就是某行某列的单元格,注意这里的下标row和column都是从1开始的,跟我平常用的数组或集合的下标有所不同。

3、对Excel的操作

3.1 打开Excel文件、释放资源

任何操作Excel的动作首先肯定是用excel应用程序,首先要new一个ApplicationClass 实例,并在最后将此实例释放。

// 创建Excel应用程序对象的一个实例,相当于我们从开始菜单打开Excel应用程序。
ApplicationClass xlsApp = new ApplicationClass();
if (xlsApp == null)
{
//对此实例进行验证,如果为null则表示运行此代码的机器可能未安装Excel
}

打开Excel文件

Workbook workbook = xlsApp.Workbooks.Open(excelFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Worksheet mySheet = workbook.Sheets[1] as Worksheet; //第一个sheet页
mySheet.Name = "testsheet"; //这里修改sheet名称

释放打开的资源

workbook.Close(true, Type.Missing, Type.Missing);
workbook = null;
xlsApp.Quit();
xlsApp = null;

3.2 对Sheet(页)的操作
复制sheet页

mySheet.Copy(Type.Missing, workbook.Sheets[1]); //复制mySheet成一个新的sheet页,复制完后的名称是mySheet页名称后加一个(2),这里就是testsheet(2),

复制完后,Worksheet的数量增加一个。注意,这里Copy方法的两个参数,指是的复制出来新的sheet页是在指定sheet页的前面还是后面,上面的例子就是指复制的sheet页在第一个sheet页的后面。
删除sheet页

xlsApp.DisplayAlerts = false; //如果想删除某个sheet页,首先要将此项设为fasle。
(xlsApp.ActiveWorkbook.Sheets[1] as Worksheet).Delete();

 选中sheet页

(xlsApp.ActiveWorkbook.Sheets[1] as Worksheet).Select(Type.Missing); //选中某个sheet页

3.3 对Excel文件的操作

另存excel文件

workbook.Saved = true;
workbook.SaveCopyAs(filepath);

3.4 其它常用功能

传入一个DataTable生成Excel

/// <summary>
///
/// </summary>
/// <param name="dt"></param>
protected void ExportExcel(DataTable dt)
{
    if (dt == null||dt.Rows.Count==0) return;
    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

    if (xlApp == null)
    {
        return;
    }
    System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
    Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
    Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
    Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
    Microsoft.Office.Interop.Excel.Range range;
    long totalCount = dt.Rows.Count;
    long rowRead = 0;
    float percent = 0;
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
        range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
        range.Interior.ColorIndex = 15;
        range.Font.Bold = true;
    }
    for (int r = 0; r < dt.Rows.Count; r++)
    {
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
        }
        rowRead++;
        percent = ((float)(100 * rowRead)) / totalCount;
    }
    xlApp.Visible = true;
}

在excel中插入图片,可以在上面的代码环境的最后加入以下代码段。

// 在Excel的指定位置加入图片
worksheet.Shapes.AddPicture("C:\\Users\\spring\\Desktop\\1.gif", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 100, 200, 200, 300);
// 在Excel的指定位置加入文本框,和里面的内容.
worksheet.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1, "123456", "Red", 15, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 150, 200);

对以上代码的调用

public void GenerateExcel()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("Name", typeof(string));
    dt.Columns.Add("Age", typeof(string));
    DataRow dr = dt.NewRow();
    dr["Name"] = "spring";
    dr["Age"] = "20";
    dt.Rows.Add(dr);
    dt.AcceptChanges();
    ExportExcel(dt);
}

4、系统性

创建一个ExcelBE类

public class ExcelBE
 {
     private int _row = 0;
     private int _col = 0;
     private string _text = string.Empty;
     private string _startCell = string.Empty;
     private string _endCell = string.Empty;
     private string _interiorColor = string.Empty;
     private bool _isMerge = false;
     private int _size = 0;
     private string _fontColor = string.Empty;
     private string _format = string.Empty;

     public ExcelBE(int row, int col, string text, string startCell, string endCell, string interiorColor, bool isMerge, int size, string fontColor, string format)
     {
         _row = row;
         _col = col;
         _text = text;
         _startCell = startCell;
         _endCell = endCell;
         _interiorColor = interiorColor;
         _isMerge = isMerge;
         _size = size;
         _fontColor = fontColor;
         _format = format;
     }

     public ExcelBE()
     { }

     public int Row
     {
         get { return _row; }
         set { _row = value; }
     }

     public int Col
     {
         get { return _col; }
         set { _col = value; }
     }

     public string Text
     {
         get { return _text; }
         set { _text = value; }
     }

     public string StartCell
     {
         get { return _startCell; }
         set { _startCell = value; }
     }

     public string EndCell
     {
         get { return _endCell; }
         set { _endCell = value; }
     }

     public string InteriorColor
     {
         get { return _interiorColor; }
         set { _interiorColor = value; }
     }

     public bool IsMerge
     {
         get { return _isMerge; }
         set { _isMerge = value; }
     }

     public int Size
     {
         get { return _size; }
         set { _size = value; }
     }

     public string FontColor
     {
         get { return _fontColor; }
         set { _fontColor = value; }
     }

     public string Formart
     {
         get { return _format; }
         set { _format = value; }
     }

 }

接下来设计一个Excel 操作的基类ExcelBase

public class ExcelBase
{
    private Microsoft.Office.Interop.Excel.Application app = null;
    private Microsoft.Office.Interop.Excel.Workbook workbook = null;
    private Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
    private Microsoft.Office.Interop.Excel.Range workSheet_range = null;

    public ExcelBase()
    {
        createDoc();
    }

    public void createDoc()
    {
        try
        {
            app = new Microsoft.Office.Interop.Excel.Application();
            app.Visible = true;
            workbook = app.Workbooks.Add(1);
            worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
        }
        catch (Exception e)
        {
            Console.Write("Error");
        }
        finally
        {
        }
    }

    public void InsertData(ExcelBE be)
    {
        worksheet.Cells[be.Row, be.Col] = be.Text;
        workSheet_range = worksheet.get_Range(be.StartCell, be.EndCell);
        workSheet_range.MergeCells = be.IsMerge;
        workSheet_range.Interior.Color = GetColorValue(be.InteriorColor);
        workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();
        workSheet_range.ColumnWidth = be.Size;
        workSheet_range.Font.Color = string.IsNullOrEmpty(be.FontColor) ? System.Drawing.Color.White.ToArgb() : System.Drawing.Color.Black.ToArgb();
        workSheet_range.NumberFormat = be.Formart;
    }

    private int GetColorValue(string interiorColor)
    {
        switch (interiorColor)
        {
            case "YELLOW":
                return System.Drawing.Color.Yellow.ToArgb();
            case "GRAY":
                return System.Drawing.Color.Gray.ToArgb();
            case "GAINSBORO":
                return System.Drawing.Color.Gainsboro.ToArgb();
            case "Turquoise":
                return System.Drawing.Color.Turquoise.ToArgb();
            case "PeachPuff":
                return System.Drawing.Color.PeachPuff.ToArgb();

            default:
                return System.Drawing.Color.White.ToArgb();
        }
    }
}

对其的调用方式

private void btnRun_Click(object sender, EventArgs e)
{
    ExcelBase excel = new ExcelBase();
    //creates the main header
    ExcelBE be = null;
    be = new ExcelBE (5, 2, "Total of Products", "B5", "D5", "YELLOW", true, 10, "n",null);
    excel.InsertData(be);
    //creates subheaders
    be = new ExcelBE (6, 2, "Sold Product", "B6", "B6", "GRAY", true, 10, "",null);
    excel.InsertData(be);
    be=new ExcelBE(6, 3, "", "C6", "C6", "GRAY", true, 10, "",null);
    excel.InsertData(be);
    be=new ExcelBE (6, 4, "Initial Total", "D6", "D6", "GRAY", true, 10, "",null);
    excel.InsertData(be);
    //add Data to cells
    be=new ExcelBE (7, 2, "114287", "B7", "B7",null,false,10,"", "#,##0");
    excel.InsertData(be);
    be=new ExcelBE (7, 3, "", "C7", "C7", null,false,10,"",null);
    excel.InsertData(be);
    be = new ExcelBE(7, 4, "129121", "D7", "D7
}

时间: 2024-08-26 08:08:48

Visual Studio 进行Excel相关开发,Microsoft.Office.Interop.Excel.dll库的相关文章

Microsoft.Office.Interop.Excel 操作 Excel

Microsoft.Office.Interop.Excel类库用于操作Excel,提供了丰富的类和函数,功能非常强大. 第一部分:类库简介 引用命名空间 using Excel = Microsoft.Office.Interop.Excel; 1,在使用类库之前,先总结以下几个类的用法 Application:Excel应用程序类,是Excel的引擎,new 一个实例. Excel.Application excelApp = new Excel.Application(); Workboo

使用 Microsoft.Office.Interop.Excel.dll 更新Excel的ColumnName

Microsoft.Office.Interop.Excel.dll 是MS提供的用于操作Excel的类库,这个类库非常强大,笔者最近遇到一个项目,需要修改Excel的列名,并且做成SSIS Package,在ssms中生存job自动执行.之前考虑使用NPOI,但是在使用NPOI时,Script task不能将NPOI自动导入到.net framework,需要执行一个gacutil的脚本,有点麻烦,既然Microsoft.Office.Interop.Excel.dll是微软的东西,肯定是已经

Assembly &#39;Microsoft.Office.Interop.Excel

编译的时候报错,都无法通过编译: Assembly 'Microsoft.Office.Interop.Excel, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' uses 'Microsoft.Vbe.Interop, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' which has a higher version

引用Microsoft.Office.Interop.Excel出现的问题

引用Microsoft.Office.Interop.Excel出现的问题 转自:http://www.hccar.com/Content,2008,6,11,75.aspx,作者:方继祥 操作背景:asp.net操作Excel 出现问题:在本地添加引用(com):Microsoft Office 11.0 Object Library,并写好程序调试正常,部署到服务器时,出现异常 Excel.Application不是对象. 初步诊断:服务器没有安装Excel组件 第一步尝试解决:对服务器安装

Microsoft.Office.Interop.Excel 放到B/S客户端失败问题 检索 COM 类工厂中 CLSID 为 {00024500-0000-0000-C000-000000000046} 的组件失败,原因是出现以下错误: 80070005 拒绝访问。

检索 COM 类工厂中 CLSID 为 {00024500-0000-0000-C000-000000000046} 的组件失败,原因是出现以下错误: 80070005 拒绝访问. (异常来自 HRESULT:0x80070005 (E_ACCESSDENIED)). 解决办法:(转) http://blog.csdn.net/wzhibin/article/details/1816690 用.net写了一个相关Excel的B/S的程序,部署到2003企业版的服务器上遇到这个错误:检索 COM

Microsoft.Office.Interop.Excel.ApplicationClass can not embedded 的问题

用c#进行开发时,要做一个excel导入功能,期间使用到Microsoft.Office.Interop.Excel程序集,在用vs2008开发的时候没有报错,将这个程序集引用到vs2010的时候,便报错了:interop type 'Microsoft.Office.Interop.Excel.ApplicationClass' cannot be embedded. 解决方法:点击程序集(DDL),右键-属性,将embed interop types 更改为false. Microsoft.

错误 1 无法嵌入互操作类型“Microsoft.Office.Interop.Excel.ApplicationClass”。请改用适用的接口

http://www.cnblogs.com/waitingfor/archive/2011/12/19/2293469.html 错误 1 无法嵌入互操作类型"Microsoft.Office.Interop.Excel.ApplicationClass".请改用适用的接口,码迷,mamicode.com 错误 1 无法嵌入互操作类型"Microsoft.Office.Interop.Excel.ApplicationClass".请改用适用的接口

报错:未能加载文件或程序集Microsoft.office.interop.excel,Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”HRESULT:0x80131040

报错:未能加载文件或程序集Microsoft.office.interop.excel,Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” 或它的某一个依赖项.找到的程序清单定义与程序集引用不匹配.异常来自HRESULT:0x80131040 WIN7环境.在装有2003的excel的XP导出成功 一直用office2010dll调试,不能导出excel 2003等旧版的. 把microsoft.office.C

添加 引用using Excel=Microsoft.Office.Interop.Excel所遇到的问题

我引用microsoft office 15.0 object library,并没有找到excel组件.但编译器中并没有报错. 很奇怪这个问题.. 添加 引用using Excel=Microsoft.Office.Interop.Excel所遇到的问题,布布扣,bubuko.com