excel导出在C#代码中应用己经很广泛了,我这里就做些总结,供自己和读者学习用。
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 |
ApplicationClass xlsApp = new ApplicationClass(); // 1. 创建Excel应用程序对象的一个实例,相当于我们从开始菜单打开Excel应用程序。 |
4 |
//对此实例进行验证,如果为null则表示运行此代码的机器可能未安装Excel |
1. 打开现有的Excel文件
1 |
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); |
2 |
Worksheet mySheet = workbook.Sheets[1] as Worksheet; //第一个sheet页 |
3 |
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 |
xlsApp.DisplayAlerts = false; //如果想删除某个sheet页,首先要将此项设为fasle。 |
2 |
(xlsApp.ActiveWorkbook.Sheets[1] as Worksheet).Delete(); |
4.选中sheet页
1 |
(xlsApp.ActiveWorkbook.Sheets[1] as Worksheet).Select(Type.Missing); //选中某个sheet页 |
5.另存excel文件
2 |
workbook.SaveCopyAs(filepath); |
6.释放excel资源
1 |
workbook.Close(true, Type.Missing, Type.Missing); |
一般的我们传入一个DataTable生成Excel代码
04 |
/// <param name="dt"></param> |
05 |
protected void ExportExcel(DataTable dt) |
07 |
if (dt == null||dt.Rows.Count==0) return; |
08 |
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); |
14 |
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture; |
15 |
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); |
16 |
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; |
17 |
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); |
18 |
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; |
19 |
Microsoft.Office.Interop.Excel.Range range; |
20 |
long totalCount = dt.Rows.Count; |
23 |
for (int i = 0; i < dt.Columns.Count; i++) |
25 |
worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName; |
26 |
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1]; |
27 |
range.Interior.ColorIndex = 15; |
28 |
range.Font.Bold = true; |
30 |
for (int r = 0; r < dt.Rows.Count; r++) |
32 |
for (int i = 0; i < dt.Columns.Count; i++) |
34 |
worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString(); |
37 |
percent = ((float)(100 * rowRead)) / totalCount; |
如果要在excel中插入图片,我们需要把代码加入一行即可,如下所示
01 |
protected void ExportExcel(DataTable dt) |
03 |
if (dt == null || dt.Rows.Count == 0) return; |
04 |
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); |
10 |
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture; |
11 |
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); |
12 |
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; |
13 |
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); |
14 |
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; |
15 |
Microsoft.Office.Interop.Excel.Range range; |
16 |
long totalCount = dt.Rows.Count; |
19 |
for (int i = 0; i < dt.Columns.Count; i++) |
21 |
worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName; |
22 |
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1]; |
23 |
range.Interior.ColorIndex = 15; |
25 |
for (int r = 0; r < dt.Rows.Count; r++) |
27 |
for (int i = 0; i < dt.Columns.Count; i++) |
31 |
worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString(); |
35 |
worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString().Replace("=", ""); |
39 |
percent = ((float)(100 * rowRead)) / totalCount; |
42 |
worksheet.Shapes.AddPicture("C:\\Users\\spring\\Desktop\\1.gif", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 100, 200, 200, 300); |
43 |
worksheet.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1, "123456", "Red", 15, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 150, 200); |
我们调用如下:
01 |
public void GenerateExcel() |
03 |
DataTable dt = new DataTable(); |
04 |
dt.Columns.Add("Name", typeof(string)); |
05 |
dt.Columns.Add("Age", typeof(string)); |
06 |
DataRow dr = dt.NewRow(); |
07 |
dr["Name"] = "spring"; |
运行结果如下所示:
其中如下代码的作用是
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:
05 |
private string _text = string.Empty; |
06 |
private string _startCell = string.Empty; |
07 |
private string _endCell = string.Empty; |
08 |
private string _interiorColor = string.Empty; |
09 |
private bool _isMerge = false; |
10 |
private int _size = 0; |
11 |
private string _fontColor = string.Empty; |
12 |
private string _format = string.Empty; |
14 |
public ExcelBE(int row, int col, string text, string startCell, string endCell, string interiorColor, bool isMerge, int size, string fontColor, string format) |
19 |
_startCell = startCell; |
21 |
_interiorColor = interiorColor; |
24 |
_fontColor = fontColor; |
46 |
set { _text = value; } |
49 |
public string StartCell |
51 |
get { return _startCell; } |
52 |
set { _startCell = value; } |
57 |
get { return _endCell; } |
58 |
set { _endCell = value; } |
61 |
public string InteriorColor |
63 |
get { return _interiorColor; } |
64 |
set { _interiorColor = value; } |
69 |
get { return _isMerge; } |
70 |
set { _isMerge = value; } |
76 |
set { _size = value; } |
79 |
public string FontColor |
81 |
get { return _fontColor; } |
82 |
set { _fontColor = value; } |
87 |
get { return _format; } |
88 |
set { _format = value; } |
接下来创建ExcelBase.cs:
01 |
public class ExcelBase |
03 |
private Microsoft.Office.Interop.Excel.Application app = null; |
04 |
private Microsoft.Office.Interop.Excel.Workbook workbook = null; |
05 |
private Microsoft.Office.Interop.Excel.Worksheet worksheet = null; |
06 |
private Microsoft.Office.Interop.Excel.Range workSheet_range = null; |
13 |
public void createDoc() |
17 |
app = new Microsoft.Office.Interop.Excel.Application(); |
19 |
workbook = app.Workbooks.Add(1); |
20 |
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1]; |
24 |
Console.Write("Error"); |
31 |
public void InsertData(ExcelBE be) |
33 |
worksheet.Cells[be.Row, be.Col] = be.Text; |
34 |
workSheet_range = worksheet.get_Range(be.StartCell, be.EndCell); |
35 |
workSheet_range.MergeCells = be.IsMerge; |
36 |
workSheet_range.Interior.Color = GetColorValue(be.InteriorColor); |
37 |
workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb(); |
38 |
workSheet_range.ColumnWidth = be.Size; |
39 |
workSheet_range.Font.Color = string.IsNullOrEmpty(be.FontColor) ? System.Drawing.Color.White.ToArgb() : System.Drawing.Color.Black.ToArgb(); |
40 |
workSheet_range.NumberFormat = be.Formart; |
43 |
private int GetColorValue(string interiorColor) |
45 |
switch (interiorColor) |
48 |
return System.Drawing.Color.Yellow.ToArgb(); |
50 |
return System.Drawing.Color.Gray.ToArgb(); |
52 |
return System.Drawing.Color.Gainsboro.ToArgb(); |
54 |
return System.Drawing.Color.Turquoise.ToArgb(); |
56 |
return System.Drawing.Color.PeachPuff.ToArgb(); |
59 |
return System.Drawing.Color.White.ToArgb(); |
调用的代码如下:
01 |
private void btnRun_Click(object sender, EventArgs e) |
03 |
ExcelBase excel = new ExcelBase(); |
04 |
//creates the main header |
06 |
be = new ExcelBE (5, 2, "Total of Products", "B5", "D5", "YELLOW", true, 10, "n",null); |
09 |
be = new ExcelBE (6, 2, "Sold Product", "B6", "B6", "GRAY", true, 10, "",null); |
11 |
be=new ExcelBE(6, 3, "", "C6", "C6", "GRAY", true, 10, "",null); |
13 |
be=new ExcelBE (6, 4, "Initial Total", "D6", "D6", "GRAY", true, 10, "",null); |
16 |
be=new ExcelBE (7, 2, "114287", "B7", "B7",null,false,10,"", "#,##0"); |
18 |
be=new ExcelBE (7, 3, "", "C7", "C7", null,false,10,"",null); |
20 |
be = new ExcelBE(7, 4, "129121", "D7", "D7", null, false, 10, "", "#,##0"); |
23 |
be = new ExcelBE(8, 2, "", "B8", "B8", null, false, 10, "", ""); |
25 |
be = new ExcelBE(8, 3, "=B7/D7", "C8", "C8", null, false, 10, "", "0.0%"); |
27 |
be = new ExcelBE(8, 4, "", "D8", "D8", null, false, 10, "", ""); |
30 |
be = new ExcelBE(9, 2, "", "B9", "D9", "GAINSBORO", true, 10, "",null); |
结果如下图所示:
标签:
本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@pclwef.cn
文章转载自:博客园