通过.NET可以操作Excel,如新建文件,新建Workbook,设置单元格等等。下面就介绍一些常用的.NET Excel操作技巧。
1. 创建一个新Excel的Application:
- Application exc = new Application();
- if (exc == null) {
- Console.WriteLine("ERROR: EXCEL couldn't be started");
- return 0;
- }
2. 让这个工程可见:
- exc.set_Visible(0, true);
3. 获取WorkBooks集合:
- Workbooks workbooks = exc.Workbooks;
4. 加入新的WorkBook:
- _Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet, 0);
5. 获取WorkSheets集合:
- _Worksheet worksheet = (_Worksheet) sheets.get_Item(1);
- if (worksheet == null) {
- Console.WriteLine ("ERROR in worksheet == null");
- }
6. 给单元格设置变量:
- Range range1 = worksheet.get_Range("C1", Missing.Value);
- if (range1 == null) {
- Console.WriteLine ("ERROR: range == null");
- }
- const int nCells = 1;
- Object[] args1 = new Object[1];
- args1[0] = nCells;
- range1.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, range1, args1);
.NET Excel操作技巧例程:
- using System;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using Excel;
- class Excel {
- public static int Main() {
- Application exc = new Application();
- if (exc == null) {
- Console.WriteLine("ERROR: EXCEL couldn't be started!");
- return 0;
- }
- exc.set_Visible(0, true);
- Workbooks workbooks = exc.Workbooks;
- _Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet, 0);
- Sheets sheets = workbook.Worksheets;
- _Worksheet worksheet = (_Worksheet) sheets.get_Item(1);
- if (worksheet == null) {
- Console.WriteLine ("ERROR: worksheet == null");
- }
- Range range1 = worksheet.get_Range("C1", Missing.Value);
- if (range1 == null) {
- Console.WriteLine ("ERROR: range == null");
- }
- const int nCells = 1;
- Object[] args1 = new Object[1];
- args1[0] = nCells;
- range1.GetType().InvokeMember("Value", BindingFlags.SetProperty, null,range1, args1);
- return 100;
- }
- }
现在我们来看看如何使用数组,他有些类似于设置单元格。仅仅需要的改变只是args2[0] = array2;
- const int nCell = 5;
- Range range2 = worksheet.get_Range("A1", "E1");
- int[] array2 = new int [nCell];
- for (int i=0; i < array2.GetLength(0); i++) {
- array2[i] = i+1;
- }
- Object[] args2 = new Object[1];
- args2[0] = array2;
- range2.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, range2, args2);
以上就介绍了一些常用的.NET Excel操作技巧,希望对大家有所帮助。
当前文章:.NETExcel操作技巧总结
链接分享:http://www.shufengxianlan.com/qtweb/news19/455469.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联