Office Com组件根据模板导出Excel

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Office Com组件根据模板导出Excel相关的知识,希望对你有一定的参考价值。

导出Excel最普遍的方式有两种,一种是使用Office Com组件,另一种是使用NPOI。

个人感觉Office Com组件功能更强大,操作Excel和设置样式等都非常方便,但它要求服务器上必须安装Office,而且受Office版本的影响。NPOI允许服务器上不安装Office,但是设置Office样式等,比Office Com组件要麻烦的多。具体使用那种要根据实际的项目来决定。本文简单列举Office Com组件一个应用小实例,NPOI的方式将在下一篇讲到。

1.添加对Microsoft.Office.Interop.Excel.dll的引用,并引入命名空间:

using Microsoft.Office.Interop;

2.创建一个DataTable并填充数据(供导出Excel使用)

 1   DataTable dt = new DataTable();
 2   dt.Columns.Add("name", System.Type.GetType("System.String"));
 3   dt.Columns.Add("age", System.Type.GetType("System.Int32"));
 4   DataRow newRow;
 5   newRow= dt.NewRow();
 6   newRow["name"] = "zhangsan";
 7   newRow["age"] = 30;
 8   dt.Rows.Add(newRow);
 9 
10   newRow = dt.NewRow();
11   newRow["name"] = "lisi";
12   newRow["age"] = 20;
13   dt.Rows.Add(newRow);

3.使用Office Com组件导出Excel

 1      #region  Microsoft.Office.Interop方式
 2            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
 3            if (app == null)//服务器上缺少Excel组件,需要安装Office软件
 4            {
 5                Response.Write("<script languge=‘javascript‘>alert(‘服务器上未安装office‘);</script>");
 6                return;
 7            }
 8            app.Visible = false;
 9            app.UserControl = true;
10            Microsoft.Office.Interop.Excel.Workbooks workbooks = app.Workbooks;
11            string path = Server.MapPath("~/Template.xlsx");
12            Microsoft.Office.Interop.Excel._Workbook workbook = workbooks.Add(path); //加载模板
13            Microsoft.Office.Interop.Excel.Sheets sheets = workbook.Sheets;
14            Microsoft.Office.Interop.Excel._Worksheet worksheet = (Microsoft.Office.Interop.Excel._Worksheet)sheets.get_Item(1); //第一个工作薄。
15            if (worksheet == null)//工作薄中没有工作表
16            {
17                Response.Write("<script languge=‘javascript‘>alert(‘第一个工作薄‘);</script>");
18                return;
19            }
20              
21             for (int i =0; i < dt.Rows.Count; i++)
22             {
23                 int _row = i + 1;
24                 worksheet.Cells[_row, 1] = dt.Rows[i]["name"].ToString().Trim();
25                 worksheet.Cells[_row, 2] = dt.Rows[i]["age"].ToString().Trim();                 
26             }
27            worksheet.Columns.AutoFit(); //保存之前自动调整列宽
28            try
29            {
30                workbook.SaveAs(Server.MapPath("~/测试.xlsx"), Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
31                Response.Write("<script languge=‘javascript‘>alert(‘保存成功‘);</script>");
32            }
33            catch (Exception)
34            {
35                Response.Write("<script languge=‘javascript‘>alert(‘运行错误‘);</script>");
36            }
37            //按顺序释放资源
38            NAR(worksheet);
39            NAR(sheets);
40            NAR(workbook);
41            NAR(workbooks);
42            app.Quit();
43            NAR(app);
44   #endregion
45            public static void NAR(object o)//释放资源的函数
46            {
47               try
48               {
49                   System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
50               }
51               catch (Exception ex)
52               {
53               }
54               finally
55               {
56                   o = null;
57               }
58           }

从而实现遍历DataTable并导出Excel的目的

全部代码:

技术分享
 1 using Microsoft.Office.Interop;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Data;
 5 using System.Linq;
 6 using System.Reflection;
 7 using System.Web;
 8 using System.Web.UI;
 9 using System.Web.UI.WebControls;
10 
11 namespace OfficeToExcel
12 {
13     public partial class ToExcel : System.Web.UI.Page
14     {
15         protected void Page_Load(object sender, EventArgs e)
16         {
17             DataTable dt = new DataTable();
18             dt.Columns.Add("name", System.Type.GetType("System.String"));
19             dt.Columns.Add("age", System.Type.GetType("System.Int32"));
20             DataRow newRow;
21            newRow= dt.NewRow();
22            newRow["name"] = "zhangsan";
23            newRow["age"] = 30;
24            dt.Rows.Add(newRow);
25 
26            newRow = dt.NewRow();
27            newRow["name"] = "lisi";
28            newRow["age"] = 20;
29            dt.Rows.Add(newRow);
30 
31            #region  Microsoft.Office.Interop方式
32            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
33            if (app == null)//服务器上缺少Excel组件,需要安装Office软件
34            {
35                Response.Write("<script languge=‘javascript‘>alert(‘服务器上未安装office‘);</script>");
36                return;
37            }
38            app.Visible = false;
39            app.UserControl = true;
40            Microsoft.Office.Interop.Excel.Workbooks workbooks = app.Workbooks;
41            string path = Server.MapPath("~/Template.xlsx");
42            Microsoft.Office.Interop.Excel._Workbook workbook = workbooks.Add(path); //加载模板
43            Microsoft.Office.Interop.Excel.Sheets sheets = workbook.Sheets;
44            Microsoft.Office.Interop.Excel._Worksheet worksheet = (Microsoft.Office.Interop.Excel._Worksheet)sheets.get_Item(1); //第一个工作薄。
45            if (worksheet == null)//工作薄中没有工作表
46            {
47                Response.Write("<script languge=‘javascript‘>alert(‘第一个工作薄‘);</script>");
48                return;
49            }
50              
51             for (int i =0; i < dt.Rows.Count; i++)
52             {
53                 int _row = i + 1;
54                 worksheet.Cells[_row, 1] = dt.Rows[i]["name"].ToString().Trim();
55                 worksheet.Cells[_row, 2] = dt.Rows[i]["age"].ToString().Trim();                 
56             }
57            worksheet.Columns.AutoFit(); //保存之前自动调整列宽
58            try
59            {
60                workbook.SaveAs(Server.MapPath("~/测试.xlsx"), Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
61                Response.Write("<script languge=‘javascript‘>alert(‘保存成功‘);</script>");
62            }
63            catch (Exception)
64            {
65                Response.Write("<script languge=‘javascript‘>alert(‘运行错误‘);</script>");
66            }
67            //按顺序释放资源
68            NAR(worksheet);
69            NAR(sheets);
70            NAR(workbook);
71            NAR(workbooks);
72            app.Quit();
73            NAR(app);
74            #endregion
75         }
76         public static void NAR(object o)//释放资源的函数
77         {
78             try
79             {
80                 System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
81             }
82             catch (Exception ex)
83             {
84             }
85             finally
86             {
87                 o = null;
88             }
89         }
90     }
91 }
View Code

 

以上是关于Office Com组件根据模板导出Excel的主要内容,如果未能解决你的问题,请参考以下文章

office组件导出excel问题

使用Spire.Doc组件利用模板导出Word文档

c# 导出数据到Excel模板

C#把DataGridView的数据导出为WPS的Excel需要引用啥组件

C#导出excel 不安装office excel情况下

使用Office组件导出Excel表格