操作Excel(C#)
2024-07-21 02:25:33
供稿:网友
来自http://www.pconline.com.cn/pcedu/empolder/gj/vc/10203/43433.html
操作excel(c#)
出处:pconline
责任编辑:zwg
[02-3-29 9:33] 作者:飞刀.net/aspcn.com
操作excel(c#)
编译:http://www.aspcn.com 飞刀
原著:arungg
来源:http://www.csharphelp.com/archives/archive241.html
前面的我就不翻译了。老外操作的是excel 2000。所有excel的程序操作都来源于excel的对象库excel9.olb.本例也只是对这个东东做一个简单的操作了解。有告诫待于朋友们的具体了解:)也算是为我们站点上天天为excel烦的兄弟们,指一条“明路”吧:)
首先的一步就是使用tlbimp这个工具将excel9.0的对象库文件excel8.olb转换成为dll,这样才能做为.net平台assembly来使用:)操作如下:
tlbimp excel9.olb excel.dll
只要有了这个excel.dll,现在我们就能使用excel的各种操作函数了。
下面就让我们具体看看c#是如何使用这些东东吧。
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);
例程:
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);
输出结果:
大家需要了解tlbimp这个工具的使用啊:)这个东东很有用,可以将普通win32程序移植到.net下面来:)