Excel操作 Microsoft.Office.Interop.Excel.dll的使用

先说说题外话,前段时间近一个月,我一直在做单据导入功能,其中就涉及到Excel操作,接触Excel后发现他的api说明并不多,好在网上有很多朋友贴出了一些代码,我在不断的挫折中吸取了很多教训,现共享出来,给大家参考。

1. 最好在客户端使用,不要在B/S服务端使用,因为会受到IIS权限和占用内存影响,多人并发操作必然完蛋

2. 需要引入两个DLL,Microsoft.Office.Interop.Excel.dll和office.dll,在加上项目的时候,会报错“类型“Microsoft.Office.Interop.Excel.ApplicationClass” 未定义构造函数无法嵌入互操作类型“Microsoft.Office.Interop.Excel.ApplicationClass”。请改用适用的接口。”,这时只需要将将引用的DLL:Microsoft.Office.Interop.Excel;的嵌入互操作类型改为false,就可以了

3. 注意Excel中sheetindex, rowindex,columnindex都是从1开始的

4. 理清Excel里面的对象(Application、Workbook、Worksheet、Range),其中Range包含行和列还有单元格,很多方法都是弱类型object,需要拆箱和装箱操作,循环读取效率并不高,所以我在读取大批量数据Excel时,采用的方式是将Excel调用另存为csv文件,再通过文本操作字符串的方式解析csv文件,读取每一行,实践证明,这样的效率比较高。解析csv文件在附件可以供大家下载

5. 客户端必须正确安装office2003或office2007,如果是安装的wps系列的,需卸载后再重新安装office

这里我贴出我封装Excel的操作类,希望能对大家有所帮助,欢迎大家指正:

   /// <summary>
    /// author by :ljun
   /// Excel工具类,目前仅支持一个工作薄的操作
   /// </summary>
    public class ExcelHelper : IDisposable
    {
        #region 构造函数

        /// <summary>
        /// 构造函数,将一个已有Excel工作簿作为模板,并指定输出路径
        /// </summary>
        /// <param name="templetFilePath">Excel模板文件路径</param>
        /// <param name="outputFilePath">输出Excel文件路径</param>
        public ExcelHelper(string templetFilePath, string outputFilePath)
        {
            if (templetFilePath == null)
                throw new Exception("Excel模板文件路径不能为空!");

            if (outputFilePath == null)
                throw new Exception("输出Excel文件路径不能为空!");

            if (!File.Exists(templetFilePath))
                throw new Exception("指定路径的Excel模板文件不存在!");

            this.templetFile = templetFilePath;
            this.outputFile = outputFilePath;

            excelApp = new Excel.ApplicationClass();
            excelApp.Visible = false;

            excelApp.DisplayAlerts = false;  //是否需要显示提示
            excelApp.AlertBeforeOverwriting = false;  //是否弹出提示覆盖

            //打开模板文件,得到WorkBook对象
            workBook = excelApp.Workbooks.Open(templetFile, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, Type.Missing, Type.Missing);

            //得到WorkSheet对象
            workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1);
        }

        /// <summary>
        /// 构造函数,新建一个工作簿
        /// </summary>
        public ExcelHelper()
        {
            excelApp = new Excel.ApplicationClass();
            excelApp.Visible = false;

            //设置禁止弹出保存和覆盖的询问提示框
            excelApp.DisplayAlerts = false;
            excelApp.AlertBeforeOverwriting = false;

            //新建一个WorkBook
            workBook = excelApp.Workbooks.Add(Type.Missing);

            //得到WorkSheet对象
            workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1);
        }

        #endregion

        #region 私有变量

        private string templetFile = null;
        private string outputFile = null;
        private object missing = System.Reflection.Missing.Value;
        private Excel.Application excelApp;
        private Excel.Workbook workBook;
        private Excel.Worksheet workSheet;
        private Excel.Range range;
        private Excel.Range range1;
        private Excel.Range range2;

        #endregion

        #region 公共属性

        /// <summary>
        /// WorkSheet数量
        /// </summary>
        public int WorkSheetCount
        {
            get { return workBook.Sheets.Count; }
        }

        /// <summary>
        /// Excel模板文件路径
        /// </summary>
        public string TempletFilePath
        {
            set { this.templetFile = value; }
        }

        /// <summary>
        /// 输出Excel文件路径
        /// </summary>
        public string OutputFilePath
        {
            set { this.outputFile = value; }
        }

        #endregion

        #region 批量写入Excel内容

        /// <summary>
        /// 将二维数组数据写入Excel文件
        /// </summary>
        /// <param name="arr">二维数组</param>
        /// <param name="top">行索引</param>
        /// <param name="left">列索引</param>
        public void ArrayToExcel(object[,] arr, int top, int left)
        {
            int rowCount = arr.GetLength(0); //二维数组行数(一维长度)
            int colCount = arr.GetLength(1); //二维数据列数(二维长度)

            range = (Excel.Range)workSheet.Cells[top, left];
            range = range.get_Resize(rowCount, colCount);
            range.FormulaArray = arr;
        }

        #endregion

        #region 行操作

        /// <summary>
        /// 插行(在指定行上面插入指定数量行)
        /// </summary>
        /// <param name="rowIndex"></param>
        /// <param name="count"></param>
        public void InsertRows(int rowIndex, int count)
        {
            try
            {
                range = (Excel.Range)workSheet.Rows[rowIndex, this.missing];
                for (int i = 0; i < count; i++)
                {
                    range.Insert(Excel.XlDirection.xlDown, missing);
                }
            }
            catch (Exception e)
            {
                this.KillExcelProcess(false);
                throw e;
            }
        }

        /// <summary>
        /// 复制行(在指定行下面复制指定数量行)
        /// </summary>
        /// <param name="rowIndex"></param>
        /// <param name="count"></param>
        public void CopyRows(int rowIndex, int count)
        {
            try
            {
                range1 = (Excel.Range)workSheet.Rows[rowIndex, this.missing];
                for (int i = 1; i <= count; i++)
                {
                    range2 = (Excel.Range)workSheet.Rows[rowIndex + i, this.missing];
                    range1.Copy(range2);
                }
            }
            catch (Exception e)
            {
                this.KillExcelProcess(false);
                throw e;
            }
        }

        /// <summary>
        /// 删除行
        /// </summary>
        /// <param name="sheetIndex"></param>
        /// <param name="rowIndex"></param>
        /// <param name="count"></param>
        public void DeleteRows(int rowIndex, int count)
        {
            try
            {
                for (int i = 0; i < count; i++)
                {
                    range = (Excel.Range)workSheet.Rows[rowIndex, this.missing];
                    range.Delete(Excel.XlDirection.xlDown);
                }
            }
            catch (Exception e)
            {
                this.KillExcelProcess(false);
                throw e;
            }
        }

        #endregion

        #region 列操作

        /// <summary>
        /// 插列(在指定列右边插入指定数量列)
        /// </summary>
        /// <param name="columnIndex"></param>
        /// <param name="count"></param>
        public void InsertColumns(int columnIndex, int count)
        {
            try
            {
                range = (Excel.Range)(workSheet.Columns[columnIndex, this.missing]);  //注意:这里和VS的智能提示不一样,第一个参数是columnindex

                for (int i = 0; i < count; i++)
                {
                    range.Insert(Excel.XlDirection.xlDown, missing);
                }
            }
            catch (Exception e)
            {
                this.KillExcelProcess(false);
                throw e;
            }
        }

        /// <summary>
        /// 删除列
        /// </summary>
        /// <param name="columnIndex"></param>
        /// <param name="count"></param>
        public void DeleteColumns(int columnIndex, int count)
        {
            try
            {
                for (int i = columnIndex + count-1; i >=  columnIndex; i--)
                {
                    ((Excel.Range)workSheet.Cells[1, i]).EntireColumn.Delete(0);
                }
            }
            catch (Exception e)
            {
                this.KillExcelProcess(false);
                throw e;
            }
        }

        #endregion

        #region 单元格操作

        /// <summary>
        /// 合并单元格,并赋值,对指定WorkSheet操作
        /// </summary>
        /// <param name="sheetIndex">WorkSheet索引</param>
        /// <param name="beginRowIndex">开始行索引</param>
        /// <param name="beginColumnIndex">开始列索引</param>
        /// <param name="endRowIndex">结束行索引</param>
        /// <param name="endColumnIndex">结束列索引</param>
        /// <param name="text">合并后Range的值</param>
        public void MergeCells(int beginRowIndex, int beginColumnIndex, int endRowIndex, int endColumnIndex, string text)
        {
            range = workSheet.get_Range(workSheet.Cells[beginRowIndex, beginColumnIndex], workSheet.Cells[endRowIndex, endColumnIndex]);

            range.ClearContents(); //先把Range内容清除,合并才不会出错
            range.MergeCells = true;

            range.Value2 = text;
            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
            range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
        }

        /// <summary>
        /// 向单元格写入数据,对当前WorkSheet操作
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <param name="columnIndex">列索引</param>
        /// <param name="text">要写入的文本值</param>
        public void SetCells(int rowIndex, int columnIndex, string text)
        {
            try
            {
                workSheet.Cells[rowIndex, columnIndex] = text;
            }
            catch
            {
                this.KillExcelProcess(false);
                throw new Exception("向单元格[" + rowIndex + "," + columnIndex + "]写数据出错!");
            }
        }

        /// <summary>
        /// 向单元格写入数据,对当前WorkSheet操作
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <param name="columnIndex">列索引</param>
        /// <param name="text">要写入的文本值</param>
        public void SetCells(int rowIndex, int columnIndex, string text, string comment)
        {
            try
            {
                workSheet.Cells[rowIndex, columnIndex] = text;
                SetCellComment(rowIndex, columnIndex, comment);
            }
            catch
            {
                this.KillExcelProcess(false);
                throw new Exception("向单元格[" + rowIndex + "," + columnIndex + "]写数据出错!");
            }
        }

        /// <summary>
        /// 向单元格写入数据,对当前WorkSheet操作
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <param name="columnIndex">列索引</param>
        /// <param name="text">要写入的文本值</param>
        public void SetCellComment(int rowIndex, int columnIndex, string comment)
        {
            try
            {
                Excel.Range range = workSheet.Cells[rowIndex, columnIndex] as Excel.Range;
                range.AddComment(comment);
            }
            catch
            {
                this.KillExcelProcess(false);
                throw new Exception("向单元格[" + rowIndex + "," + columnIndex + "]写数据出错!");
            }
        }

        /// <summary>
        /// 单元格背景色及填充方式
        /// </summary>
        /// <param name="startRow">起始行</param>
        /// <param name="startColumn">起始列</param>
        /// <param name="endRow">结束行</param>
        /// <param name="endColumn">结束列</param>
        /// <param name="color">颜色索引</param>
        public void SetCellsBackColor(int startRow, int startColumn, int endRow, int endColumn, ColorIndex color)
        {
            Excel.Range range = excelApp.get_Range(excelApp.Cells[startRow, startColumn], excelApp.Cells[endRow, endColumn]);
            range.Interior.ColorIndex = color;
        }

        #endregion

        #region 保存文件

        /// <summary>
        /// 另存文件
        /// </summary>
        public void SaveAsFile()
        {
            if (this.outputFile == null)
                throw new Exception("没有指定输出文件路径!");

            try
            {
                workBook.SaveAs(outputFile, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                this.Quit();
            }
        }

        /// <summary>
        /// 将Excel文件另存为指定格式
        /// </summary>
        /// <param name="format">HTML,CSV,TEXT,EXCEL,XML</param>
        public void SaveAsFile(SaveAsFileFormat format)
        {
            if (this.outputFile == null)
                throw new Exception("没有指定输出文件路径!");

            try
            {
                switch (format)
                {
                    case SaveAsFileFormat.HTML:
                        {
                            workBook.SaveAs(outputFile, Excel.XlFileFormat.xlHtml, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
                            break;
                        }
                    case SaveAsFileFormat.CSV:
                        {
                            workBook.SaveAs(outputFile, Excel.XlFileFormat.xlCSV, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
                            break;
                        }
                    case SaveAsFileFormat.TEXT:
                        {
                            workBook.SaveAs(outputFile, Excel.XlFileFormat.xlUnicodeText, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
                            break;
                        }
                    case SaveAsFileFormat.XML:
                        {
                            workBook.SaveAs(outputFile, Excel.XlFileFormat.xlXMLSpreadsheet, Type.Missing, Type.Missing,
                             Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
                             Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                            break;
                        }
                    default:
                        {
                            workBook.SaveAs(outputFile, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
                            break;
                        }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                this.Quit();
            }
        }

        #endregion

        #region 杀进程释放资源

        /// <summary>
        /// 结束Excel进程
        /// </summary>
        public void KillExcelProcess(bool bAll)
        {
            if (bAll)
            {
                KillAllExcelProcess();
            }
            else
            {
                KillSpecialExcel();
            }
        }

        [DllImport("user32.dll", SetLastError = true)]
        static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

        /// <summary>
        /// 杀特殊进程的Excel
        /// </summary>
        public void KillSpecialExcel()
        {
            try
            {
                if (excelApp != null)
                {
                    int lpdwProcessId;
                    GetWindowThreadProcessId((IntPtr)excelApp.Hwnd, out lpdwProcessId);

                    if (lpdwProcessId > 0)    //c-s方式
                    {
                        System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
                    }
                    else
                    {
                        Quit();
                    }
                }
            }
            catch { }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Quit()
        {
            if (workBook != null)
                workBook.Close(null, null, null);
            if (excelApp != null)
            {
                excelApp.Workbooks.Close();
                excelApp.Quit();
            }
            if (range != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
                range = null;
            }
            if (range1 != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(range1);
                range1 = null;
            }
            if (range2 != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(range2);
                range2 = null;
            }
            if (workSheet != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
                workSheet = null;
            }
            if (workBook != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
                workBook = null;
            }
            if (excelApp != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
                excelApp = null;
            }
            GC.Collect();
        }

        /// <summary>
        /// 接口方法 释放资源
        /// </summary>
        public void Dispose()
        {
            Quit();
        }

        #endregion

        #region 静态方法

        /// <summary>
        /// 杀Excel进程
        /// </summary>
        public static void KillAllExcelProcess()
        {
            Process[] myProcesses;
            myProcesses = Process.GetProcessesByName("Excel");

            //得不到Excel进程ID,暂时只能判断进程启动时间
            foreach (Process myProcess in myProcesses)
            {
                myProcess.Kill();
            }
        }

        /// <summary>
        /// 打开相应的excel
        /// </summary>
        /// <param name="filepath"></param>
        public static void OpenExcel(string filepath)
        {
            Excel.Application xlsApp = new Excel.Application();
            xlsApp.Workbooks.Open(filepath);
            xlsApp.Visible = true;
        }

        #endregion

    }

    /// <summary>
    /// 常用颜色定义,对就Excel中颜色名
    /// </summary>
    public enum ColorIndex
    {
        无色 = -4142,
        自动 = -4105,
        黑色 = 1,
        褐色 = 53,
        橄榄 = 52,
        深绿 = 51,
        深青 = 49,
        深蓝 = 11,
        靛蓝 = 55,
        灰色80 = 56,
        深红 = 9,
        橙色 = 46,
        深黄 = 12,
        绿色 = 10,
        青色 = 14,
        蓝色 = 5,
        蓝灰 = 47,
        灰色50 = 16,
        红色 = 3,
        浅橙色 = 45,
        酸橙色 = 43,
        海绿 = 50,
        水绿色 = 42,
        浅蓝 = 41,
        紫罗兰 = 13,
        灰色40 = 48,
        粉红 = 7,
        金色 = 44,
        黄色 = 6,
        鲜绿 = 4,
        青绿 = 8,
        天蓝 = 33,
        梅红 = 54,
        灰色25 = 15,
        玫瑰红 = 38,
        茶色 = 40,
        浅黄 = 36,
        浅绿 = 35,
        浅青绿 = 34,
        淡蓝 = 37,
        淡紫 = 39,
        白色 = 2
    }

    /// <summary>
    /// HTML,CSV,TEXT,EXCEL,XML
    /// </summary>
    public enum SaveAsFileFormat
    {
        HTML,
        CSV,
        TEXT,
        EXCEL,
        XML
    }

Excel操作 Microsoft.Office.Interop.Excel.dll的使用

时间: 2024-08-24 01:59:42

Excel操作 Microsoft.Office.Interop.Excel.dll的使用的相关文章

NPOI写Excel,Microsoft.Office.Interop.excel.dll 转换Excel为PDF

首先要引用NPOI动态库和Microsoft.Office.Interop.excel.dll (Microsoft.Office.Interop.excel.dll 下载链接,下载以后解压文件,把Microsoft.Office.Interop.excel.dll拷贝到项目下,添加引用.NPOI的添加则项目选中右键使用管理NuGet管理程序包,nuget添加NPOI即可) 上述工作完成,下面直接代码 using System;using System.Collections.Generic;u

c#操作excel方式三:使用Microsoft.Office.Interop.Excel.dll读取Excel文件

1.引用Microsoft.Office.Interop.Excel.dll 2.引用命名空间.使用别名 [csharp] view plaincopy using System.Reflection; using Excel = Microsoft.Office.Interop.Excel; 3.写入excel 写入函数 [csharp] view plaincopy public void ToExcel(string strTitle) { int nMax = 9; int nMin =

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

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 Tool

使用 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是微软的东西,肯定是已经

vs引用Microsoft.Office.Interop.Excel.dll版本问题

错误信息: {"检索 COM 类工厂中 CLSID 为 {00020819-0000-0000-C000-000000000046} 的组件失败,原因是出现以下错误: 80040154 没有注册类 (异常来自 HRESULT:0x80040154 (REGDB_E_CLASSNOTREG))."} 开始以为权限问题: dcomcnfg.exe 安全--启动与激活权限 访问权限自定义: 问题并没解决: excle组件问题大多都是权限和版本问题, 错误原因:引用Microsoft.Offi

C#操作Office- Cannot find the interop type that matches the embedded interop type &#39;Microsoft.Office.Interop.Excel.Application&#39;

网上说 2003 -> 11.0, 2007 -> 12.0. 因为平时提示"Are you missing an assembly reference?",都是没有引用库文件,但是明明我已经添加好引用了,还是报错.机器上安装的是Office2010,但是在库引用中,v14.0的是不行,Office 2010中的 Excel还是用v12.0. 处理题目中的错误,是将库文件中的"Embedded Interop Type"属性设置为false即可.(突然记

引用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的用法以及利用Microsoft.Office.Interop.Excel将web页面转成PDF

1.常见用法           using Microsoft.Office.Interop.Excel; 1)新建一个Excel ApplicationClass ExcelApp = New ApplicationClass();    Microsoft.Office.Interop.Excel.Workbook book = ExcelApp.Workbooks.Add(); 2) 更改 Excel 标题栏: ExcelApp.Caption := '应用程序调用 Micr