.NET操作Excel是一个很有用的功能。本文介绍一些常用的.NET Excel操作技巧。
通过.NET可以操作Excel,如新建文件,新建Workbook,设置单元格等等。下面就介绍一些常用的.NET Excel操作技巧。
1. 创建一个新Excel的Application:
复制
1. Application exc = new Application();
2. if (exc == null) {
3. Console.WriteLine("ERROR: EXCEL couldn't be started");
4. return 0;
5. }
2. 让这个工程可见:
复制
1. exc.set_Visible(0, true);
3. 获取WorkBooks集合:
复制
1. Workbooks workbooks = exc.Workbooks;
4. 加入新的WorkBook:
复制
1. _Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet, 0);
5. 获取WorkSheets集合:
复制
1. _Worksheet worksheet = (_Worksheet) sheets.get_Item(1);
2. if (worksheet == null) {
3. Console.WriteLine ("ERROR in worksheet == null");
4. }
6. 给单元格设置变量:
复制
1. Range range1 = worksheet.get_Range("C1", Missing.Value);
2. if (range1 == null) {
3. Console.WriteLine ("ERROR: range == null");
4. }
5. const int nCells = 1;
6. Object[] args1 = new Object[1];
7. args1[0] = nCells;
8. range1.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, range1, args1);
.NET Excel操作技巧例程:
复制
1. using System;
2. using System.Reflection;
3. using System.Runtime.InteropServices;
4. using Excel;
5.
6. class Excel {
7. public static int Main() {
8. Application exc = new Application();
9. if (exc == null) {
10. Console.WriteLine("ERROR: EXCEL couldn't be started!");
11. return 0;
12. }
13.
14. exc.set_Visible(0, true);
15. Workbooks workbooks = exc.Workbooks;
16. _Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet, 0);
17. Sheets sheets = workbook.Worksheets;
18.
19. _Worksheet worksheet = (_Worksheet) sheets.get_Item(1);
20. if (worksheet == null) {
21. Console.WriteLine ("ERROR: worksheet == null");
22. }
23.
24. Range range1 = worksheet.get_Range("C1", Missing.Value);
25. if (range1 == null) {
26. Console.WriteLine ("ERROR: range == null");
27. }
28. const int nCells = 1;
29. Object[] args1 = new Object[1];
30. args1[0] = nCells;
31. range1.GetType().InvokeMember("Value", BindingFlags.SetProperty, null,range1, args1);
32. return 100;
33. }
34. }
现在我们来看看如何使用数组,他有些类似于设置单元格。仅仅需要的改变只是args2[0] = array2;
复制
1. const int nCell = 5;
2. Range range2 = worksheet.get_Range("A1", "E1");
3. int[] array2 = new int [nCell];
4. for (int i=0; i < array2.GetLength(0); i++) {
5. array2[i] = i+1;
6. }
7. Object[] args2 = new Object[1];
8. args2[0] = array2;
9. range2.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, range2, args2);
以上就介绍了一些常用的.NET Excel操作技巧,希望对大家有所帮助。
>>>>>>点击进入Office办公软件专题
上一篇:如何用Excel操作Oracle
¥10.00
¥10.00
¥99.00
¥168.00
¥10.00
¥168.00