您的位置:首页 > 编程语言 > C#

C#操作Excel知识点

2012-01-04 16:29 495 查看
C#操作Excel知识点

近期在使用C#操作excel,主要是读取excel模板,复制其中的模板sheet页,生成多个sheet页填充相应数据后另存到excel文件,所用到的知识点如下。

  一、添加引用和命名空间

  添加Microsoft.Office.Interop.Excel引用,它的默认路径是C:\Program Files\Microsoft Visual Studio 9.0\Visual Studio Tools for Office\PIA\Office12\Microsoft.Office.Interop.Excel.dll

  代码中添加引用using Microsoft.Office.Interop.Excel;

  二、Excel类的简单介绍

  此命名空间下关于Excel类的结构分别为:

  ApplicationClass - 就是我们的excel应用程序。

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

  Worksheet - 就是excel文件中的一个个sheet页。

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

  知道了上述基本知识后,利用此类来操作excel就清晰了很多。

  三、Excel的操作

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

  ApplicationClass xlsApp = new ApplicationClass();  // 1. 创建Excel应用程序对象的一个实例,相当于我们从开始菜单打开Excel应用程序。

  if (xlsApp == null)

  {

  //对此实例进行验证,如果为null则表示运行此代码的机器可能未安装Excel

  }

  1. 打开现有的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名称

  2.复制sheet页

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

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

  3.删除sheet页

  xlsApp.DisplayAlerts = false; //如果想删除某个sheet页,首先要将此项设为fasle。

  (xlsApp.ActiveWorkbook.Sheets[1] as Worksheet).Delete();

  4.选中sheet页

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

  5.另存excel文件

  workbook.Saved = true;

  workbook.SaveCopyAs(filepath);

  6.释放excel资源

  workbook.Close(true, Type.Missing, Type.Missing);

  workbook = null;

  xlsApp.Quit();

  xlsApp = null;

添加的文件头:

     using System.Reflection; // 引用这个才能使用Missing字段

     using Excel;

        Excel.ApplicationClass excel = new Excel.ApplicationClass();

               excel.Visible = true;       //激活Excel

            Workbook wBook   = excel.Workbooks.Add(true);

       //     Worksheet wSheet = (Excel._Worksheet)wBook.ActiveSheet;

            Worksheet wSheet = (Excel.Worksheet)wBook.ActiveSheet;     

                    excel.Cells[3, 5] = "本公司电话: " + Phone;

                    excel.Cells[4, 5] = "本公司传真: " + Zhen;

                    excel.Cells[5, 5] = "联系人: " + ComName;

                    excel.Cells[4, 1] = "客户: " + CustomerName;

                    excel.Cells[5, 1] = "联系人: " + Associate;

                    excel.Cells[3, 8] = "户名:";

                    excel.Cells[3, 9] = AccountName;

                    excel.Cells[4, 8] = "开户行:";

                    excel.Cells[4, 9] = BranchName;

                    excel.Cells[5, 8] = "帐号:";

                    excel.Cells[5, 9] = "'" + AccountID;

                       //设置禁止弹出保存和覆盖的询问提示框

            excel.DisplayAlerts = false;

            excel.AlertBeforeOverwriting = false;

            //保存工作薄

          //  wBook.Save();

            //每次保存激活的表,这样才能多次操作保存不同的Excel表,默认保存位置是在”我的文档"

           

            excel.Cells.Font.Size = 12;

            excel.Cells.Font.Bold = false;

          //  Excel.Range m_objRange = m_objRange.get_Range(1, 3);

            wSheet.get_Range(excel.Cells[1, 3], excel.Cells[1, 3]).Font.Size = 24;

            wSheet.get_Range(excel.Cells[1, 3], excel.Cells[1, 3]).Font.Bold = true;

            wSheet.get_Range(excel.Cells[3, 1], excel.Cells[3, 1]).Font.ColorIndex = 3;//此处设为红色,不能用Font.Color来设置颜色

          //  m_objRange.Cells.Font.Size = 24;

          //  m_objRange.Cells.Font.Bold = true;

            excel.ActiveWorkbook.SaveCopyAs(filename);

         excel.Quit();

      代码注释部分只是简单描述各语句的原由,个别的还是值得推敲的。

      语句一  Workbook wBook   = excel.Workbooks.Add(true);

Workbooks.Add的参数是个object类型,通常使用true或null,表明工作簿在默认文档下创建,或者使用枚举值

      XlWBATemplate.xlWBATWorksheet,但如果传入一个excel完整文件名,却相当于打开已有工作簿。

      语句二  Worksheet wSheet = (Excel.Worksheet)wBook.ActiveSheet;    这样可以操作多个工作表的话,实例化之后加入到wBook.Worksheets中去。如果是打开已存在的工作簿,这条语句也可能会报错,最好是调用wBook.ActiveSheet来获取或者再加些判断。

      语句三

       excel.ActiveWorkbook.SaveCopyAs(filename);这两句代码至关重要,而且必不可少,否则,保存时会弹出“是否保存sheet1.xls”的对话框。判断当前激活的表,并保存这个表。

      语句四 excel.Quit();

      这个关闭一直有疑点,因为C#操作com非托管对象时,凭借Quit()还没有释放掉对象,excel进程不一定会终止,于是,有人使用KillProcess()来处理,我个人认为这不是一个好主意,可能会破坏其它正在执行的excel进程。目前我使用app

      =

      null;权作安慰吧。不过有一点是一定要做到,就是在Quit()前不能再有任何更改,不然还是会弹出保存的对话框。所以退出前确保一定是执行过WorkBook或是Application的Save()方法的。

 

附:

public static void Export2Xls(DataTable data, string filename, bool exportHeader = true)

        {

            if (System.IO.File.Exists(filename))

                System.IO.File.Delete(filename);

            Excel._Application xlsApp = null;

            Excel._Workbook xlsBook = null;

            Excel._Worksheet xstSheet = null;

            try

            {

                xlsApp = new Excel.ApplicationClass();

                xlsBook = xlsApp.Workbooks.Add();

                xstSheet = (Excel._Worksheet)xlsBook.Worksheets[1];

                var buffer = new StringBuilder();

                if (exportHeader)

                {

                    // Excel中列与列之间按照Tab隔开

                    foreach (DataColumn col in data.Columns)

                        buffer.Append(col.ColumnName + "\t");

                    buffer.AppendLine();

                }

                foreach (DataRow row in data.Rows)

                {

                    foreach (DataColumn col in data.Columns)

                        buffer.Append(row[col].ToString() + "\t");

                    buffer.AppendLine();

                }

                System.Windows.Forms.Clipboard.SetDataObject("");

                // 放入剪切板

                System.Windows.Forms.Clipboard.SetDataObject(buffer.ToString());

                var range = (Excel.Range)xstSheet.Cells[1, 1];

                range.Select();

                xstSheet.Paste();

                // 清空剪切板

                System.Windows.Forms.Clipboard.SetDataObject("");

                xlsBook.SaveAs(filename);

            }

            finally

            {

                if (xlsBook != null)

                    xlsBook.Close();

                if (xlsApp != null)

                    xlsApp.Quit();

                // finally里清空Com对象

                Marshal.ReleaseComObject(xlsApp);

                Marshal.ReleaseComObject(xlsBook);

                Marshal.ReleaseComObject(xstSheet);

                xstSheet = null;

                xlsBook = null;

                xlsApp = null;

            }

        }

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息