C# 导出Excel的示例
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 实例,并在最后将此实例释放。
1
2
3
4
5
|
ApplicationClass xlsApp = new ApplicationClass(); // 1. 创建Excel应用程序对象的一个实例,相当于我们从开始菜单打开Excel应用程序。 if (xlsApp == null ) { //对此实例进行验证,如果为null则表示运行此代码的机器可能未安装Excel } |
1. 打开现有的Excel文件
1
2
3
|
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页
1
|
mySheet.Copy(Type.Missing, workbook.Sheets[1]); //复制mySheet成一个新的sheet页,复制完后的名称是mySheet页名称后加一个(2),这里就是testsheet(2),复制完后,Worksheet的数量增加一个 |
注意 这里Copy方法的两个参数,指是的复制出来新的sheet页是在指定sheet页的前面还是后面,上面的例子就是指复制的sheet页在第一个sheet页的后面。
3.删除sheet页
1
2
|
xlsApp.DisplayAlerts = false ; //如果想删除某个sheet页,首先要将此项设为fasle。 (xlsApp.ActiveWorkbook.Sheets[1] as Worksheet).Delete(); |
4.选中sheet页
1
|
(xlsApp.ActiveWorkbook.Sheets[1] as Worksheet).Select(Type.Missing); //选中某个sheet页 |
5.另存excel文件
1
2
|
workbook.Saved = true ; workbook.SaveCopyAs(filepath); |
6.释放excel资源
1
2
3
4
|
workbook.Close( true , Type.Missing, Type.Missing); workbook = null ; xlsApp.Quit(); xlsApp = null ; |
一般的我们传入一个DataTable生成Excel代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
/// <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中插入图片,我们需要把代码加入一行即可,如下所示
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
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; } for ( int r = 0; r < dt.Rows.Count; r++) { for ( int i = 0; i < dt.Columns.Count; i++) { try { worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString(); } catch { worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString().Replace( "=" , "" ); } } rowRead++; percent = (( float )(100 * rowRead)) / totalCount; } worksheet.Shapes.AddPicture( "C:\\Users\\spring\\Desktop\\1.gif" , Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 100, 200, 200, 300); worksheet.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1, "123456" , "Red" , 15, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 150, 200); xlApp.Visible = true ; } |
我们调用如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
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); } |
运行结果如下所示:
其中如下代码的作用是
1
|
worksheet.Shapes.AddPicture( "C:\\Users\\spring\\Desktop\\1.gif" , Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 100, 200, 200, 300); |
在Excel的指定位置加入图片
1
|
worksheet.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1, "123456" , "Red" , 15, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 150, 200); |
在Excel的指定位置加入文本框,和里面的内容.
我们可以这样来设计一个ExcelBase的基类:
先创建一个ExcelBE.cs:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
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; } } } |
接下来创建ExcelBase.cs:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
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(); } } } |
调用的代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
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" , null , false , 10, "" , "#,##0" ); excel.InsertData(be); //add percentage row be = new ExcelBE(8, 2, "" , "B8" , "B8" , null , false , 10, "" , "" ); excel.InsertData(be); be = new ExcelBE(8, 3, "=B7/D7" , "C8" , "C8" , null , false , 10, "" , "0.0%" ); excel.InsertData(be); be = new ExcelBE(8, 4, "" , "D8" , "D8" , null , false , 10, "" , "" ); excel.InsertData(be); //add empty divider be = new ExcelBE(9, 2, "" , "B9" , "D9" , "GAINSBORO" , true , 10, "" , null ); excel.InsertData(be); } |
结果如下图所示:
C# 导出Excel的示例的更多相关文章
- C# 导出Excel的示例(转)
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.W ...
- Java利用POI实现导入导出Excel表格示例代码
转自:https://www.jb51.net/article/95526.htm 介绍 Jakarta POI 是一套用于访问微软格式文档的Java API.Jakarta POI有很多组件组成,其 ...
- Jquery easyui datagrid 导出Excel
From:http://www.cnblogs.com/weiqt/articles/4022399.html datagrid的扩展方法,用于将当前的数据生成excel需要的内容. 1 <sc ...
- easyui 导出 excel
<div style="margin-bottom:5px" id="tb"> <a href="#" class=&qu ...
- 如何使用JavaScript实现前端导入和导出excel文件
一.SpreadJS 简介 SpreadJS 是一款基于 HTML5 的纯 JavaScript 电子表格和网格功能控件,以“高速低耗.纯前端.零依赖”为产品特色,可嵌入任何操作系统,同时满足 .NE ...
- 分享我基于NPOI+ExcelReport实现的导入与导出EXCEL类库:ExcelUtility (续2篇-模板导出综合示例)
自ExcelUtility类推出以来,经过项目中的实际使用与不断完善,现在又做了许多的优化并增加了许多的功能,本篇不再讲述原理,直接贴出示例代码以及相关的模板.结果图,以便大家快速掌握,另外这些示例说 ...
- NPOI导出Excel示例
摘要:使用开源程序NPOI导出Excel示例.NPOI首页地址:http://npoi.codeplex.com/,NPOI示例博客:http://tonyqus.sinaapp.com/. 示例编写 ...
- SpringBoot使用Easypoi导出excel示例
SpringBoot使用Easypoi导出excel示例 https://blog.csdn.net/justry_deng/article/details/84842111
- asp.net导出excel示例代码
asp.net导出excel的简单方法. excel的操作,最常用的就是导出和导入. 本例使用NPOI实现. 代码:/// <summary> ); ; ...
随机推荐
- python Windows和Linux路径表示问题
Windows下路径是用‘\\’表示也可以使用'/',但是Linux下路径都是‘/’表示. 因为python是跨平台的,有时候程序迁移会出现错误. 解决办法1 可全部使用‘/’表示 解决办法2 我们可 ...
- jQuery val()方法及valHooks源码解读
val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) {//无参数 ...
- Asp.Net实现记录历史访问人数和当前在线人数
************************************在Global.asax中如下************************ <%@ Import Namespace= ...
- 分布式系统ID生成办法
前言 一般单机或者单数据库的项目可能规模比较小,适应的场景也比较有限,平台的访问量和业务量都较小,业务ID的生成方式比较原始但是够用,它并没有给这样的系统带来问题和瓶颈,所以这种情况下我们并没有对此给 ...
- 怎样将python的文件转化为windows的可执行程序
最近我在刚入手python,其中就学到了怎样将python的py格式文件转化为windows的exe执行程序, 是这样的,首先要创建一个py文件,这里给截图吧 接下来就以这个python文件为例创建一 ...
- Somethings about Floors题解
题目内容:一个楼梯有N级(N >=0), 每次走1级或2级, 从底走到顶一共有多少种走法? 输入要求:只有一行输入,并且只有一个数N(如果N > 20,则N = N%21,即保证N的范围控 ...
- How to install Eclipse?
http://askubuntu.com/questions/26632/how-to-install-eclipse How to install Eclipse? up vote113down v ...
- cookie安全
www.baidu.com host 文件 定义 a.baidu.com 为127.0.01 本地编写php程序 读取浏览器发送给 a.baidu.com的cookie 会把 .baidu.com域下 ...
- 如何让Spring MVC显示自定义的404 Not Found页面
不知道大家对千篇一律的404 Not Found的错误页面是否感到腻歪了?其实通过很简单的配置就能够让Spring MVC显示您自定义的404 Not Found错误页面. 在WEB-INF的web. ...
- 什么是闭包(Closure)?
http://kb.cnblogs.com/page/111780/ 这个问题是在最近一次英格兰Brighton ALT.NET Beers活动中提出来的.我发现,如果不用代码来演示,你很难单用话语把 ...