彩票走势图

C# 导出Excel的示例

转帖|其它|编辑:郝浩|2011-08-15 14:56:17.000|阅读 1567 次

概述:excel导出在C#代码中应用己经很广泛了,我这里就做些总结,供自己和读者学习用。

# 慧都年终大促·界面/图表报表/文档/IDE等千款热门软控件火热促销中 >>

  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应用程序。
2 if (xlsApp == null)
3 {
4 //对此实例进行验证,如果为null则表示运行此代码的机器可能未安装Excel
5 }

   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文件

 
1 workbook.Saved = true;
2 workbook.SaveCopyAs(filepath);

6.释放excel资源

 
1 workbook.Close(true, Type.Missing, Type.Missing);
2 workbook = null;
3 xlsApp.Quit();
4 xlsApp = null;

  一般的我们传入一个DataTable生成Excel代码

 
01 /// <summary>
02 ///
03 /// </summary>
04 /// <param name="dt"></param>
05 protected void ExportExcel(DataTable dt)
06 {
07     if (dt == null||dt.Rows.Count==0) return;
08     Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
09  
10     if (xlApp == null)
11     {
12         return;
13     }
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;
21     long rowRead = 0;
22     float percent = 0;
23     for (int i = 0; i < dt.Columns.Count; i++)
24     {
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;
29     }
30     for (int r = 0; r < dt.Rows.Count; r++)
31     {
32         for (int i = 0; i < dt.Columns.Count; i++)
33         {
34             worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
35         }
36         rowRead++;
37         percent = ((float)(100 * rowRead)) / totalCount;
38     }
39     xlApp.Visible = true;
40 }

  如果要在excel中插入图片,我们需要把代码加入一行即可,如下所示

 
01 protected void ExportExcel(DataTable dt)
02 {
03     if (dt == null || dt.Rows.Count == 0) return;
04     Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
05  
06     if (xlApp == null)
07     {
08         return;
09     }
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;
17     long rowRead = 0;
18     float percent = 0;
19     for (int i = 0; i < dt.Columns.Count; i++)
20     {
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;
24     }
25     for (int r = 0; r < dt.Rows.Count; r++)
26     {
27         for (int i = 0; i < dt.Columns.Count; i++)
28         {
29             try
30             {
31                 worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
32             }
33             catch
34             {
35                 worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString().Replace("=", "");
36             }
37         }
38         rowRead++;
39         percent = ((float)(100 * rowRead)) / totalCount;
40     }
41      
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);
44     xlApp.Visible = true;
45 }
 

  我们调用如下:

 
01 public void GenerateExcel()
02 {
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";
08     dr["Age"] = "20";
09     dt.Rows.Add(dr);
10     dt.AcceptChanges();
11     ExportExcel(dt);
12 }

  运行结果如下所示:

  image

  其中如下代码的作用是

 
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:

 
01 public class ExcelBE
02  {
03      private int _row = 0;
04      private int _col = 0;
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;
13  
14      public ExcelBE(int row, int col, string text, string startCell, string endCell, string interiorColor, bool isMerge, int size, string fontColor, string format)
15      {
16          _row = row;
17          _col = col;
18          _text = text;
19          _startCell = startCell;
20          _endCell = endCell;
21          _interiorColor = interiorColor;
22          _isMerge = isMerge;
23          _size = size;
24          _fontColor = fontColor;
25          _format = format;
26      }
27  
28      public ExcelBE()
29      { }
30  
31      public int Row
32      {
33          get { return _row; }
34          set { _row = value; }
35      }
36  
37      public int Col
38      {
39          get { return _col; }
40          set { _col = value; }
41      }
42  
43      public string Text
44      {
45          get { return _text; }
46          set { _text = value; }
47      }
48  
49      public string StartCell
50      {
51          get { return _startCell; }
52          set { _startCell = value; }
53      }
54  
55      public string EndCell
56      {
57          get { return _endCell; }
58          set { _endCell = value; }
59      }
60  
61      public string InteriorColor
62      {
63          get { return _interiorColor; }
64          set { _interiorColor = value; }
65      }
66  
67      public bool IsMerge
68      {
69          get { return _isMerge; }
70          set { _isMerge = value; }
71      }
72  
73      public int Size
74      {
75          get { return _size; }
76          set { _size = value; }
77      }
78  
79      public string FontColor
80      {
81          get { return _fontColor; }
82          set { _fontColor = value; }
83      }
84  
85      public string Formart
86      {
87          get { return _format; }
88          set { _format = value; }
89      }
90  
91  }
 

  接下来创建ExcelBase.cs:

 
01 public class ExcelBase
02 {
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;
07  
08     public ExcelBase()
09     {
10         createDoc();
11     }
12  
13     public void createDoc()
14     {
15         try
16         {
17             app = new Microsoft.Office.Interop.Excel.Application();
18             app.Visible = true;
19             workbook = app.Workbooks.Add(1);
20             worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
21         }
22         catch (Exception e)
23         {
24             Console.Write("Error");
25         }
26         finally
27         {
28         }
29     }
30  
31     public void InsertData(ExcelBE be)
32     {
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;
41     }
42  
43     private int GetColorValue(string interiorColor)
44     {
45         switch (interiorColor)
46         {
47             case "YELLOW":
48                 return System.Drawing.Color.Yellow.ToArgb();
49             case "GRAY":
50                 return System.Drawing.Color.Gray.ToArgb();
51             case "GAINSBORO":
52                 return System.Drawing.Color.Gainsboro.ToArgb();
53             case "Turquoise":
54                 return System.Drawing.Color.Turquoise.ToArgb();
55             case "PeachPuff":
56                 return System.Drawing.Color.PeachPuff.ToArgb();
57  
58             default:
59                 return System.Drawing.Color.White.ToArgb();
60         }
61     }
62 }
 

  调用的代码如下:

 
01 private void btnRun_Click(object sender, EventArgs e)
02 {
03     ExcelBase excel = new ExcelBase();
04     //creates the main header
05     ExcelBE be = null;
06     be = new ExcelBE (5, 2, "Total of Products", "B5", "D5", "YELLOW", true, 10, "n",null);
07     excel.InsertData(be);
08     //creates subheaders
09     be = new ExcelBE (6, 2, "Sold Product", "B6", "B6", "GRAY", true, 10, "",null);
10     excel.InsertData(be);
11     be=new ExcelBE(6, 3, "", "C6", "C6", "GRAY", true, 10, "",null);
12     excel.InsertData(be);
13     be=new ExcelBE (6, 4, "Initial Total", "D6", "D6", "GRAY", true, 10, "",null);
14     excel.InsertData(be);
15     //add Data to cells
16     be=new ExcelBE (7, 2, "114287", "B7", "B7",null,false,10,"", "#,##0");
17     excel.InsertData(be);
18     be=new ExcelBE (7, 3, "", "C7", "C7", null,false,10,"",null);
19     excel.InsertData(be);
20     be = new ExcelBE(7, 4, "129121", "D7", "D7", null, false, 10, "", "#,##0");
21     excel.InsertData(be);
22     //add percentage row
23     be = new ExcelBE(8, 2, "", "B8", "B8", null, false, 10, "", "");
24     excel.InsertData(be);
25     be = new ExcelBE(8, 3, "=B7/D7", "C8", "C8", null, false, 10, "", "0.0%");
26     excel.InsertData(be);
27     be = new ExcelBE(8, 4, "", "D8", "D8", null, false, 10, "", "");
28     excel.InsertData(be);
29     //add empty divider
30     be = new ExcelBE(9, 2, "", "B9", "D9", "GAINSBORO", true, 10, "",null);
31     excel.InsertData(be);  
32  
33 }
 

  结果如下图所示:

  image


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@pclwef.cn

文章转载自:博客园

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP