設(shè)置Excel(C#)
發(fā)表時(shí)間:2024-02-15 來(lái)源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]前面的我就不翻譯了。老外操作的是Excel 2000。所有Excel的程序操作都來(lái)源于Excel的對(duì)象庫(kù)Excel9.olb.本例也只是對(duì)這個(gè)東東做一個(gè)簡(jiǎn)單的操作了解。有告誡待于朋友們的具體了解:)也算是為我們站點(diǎn)上天天為Excel煩的兄弟們,指一條“明路”吧:)首先的一步就是使用Tlbimp這個(gè)...
前面的我就不翻譯了。老外操作的是Excel 2000。所有Excel的程序操作都來(lái)源于Excel的對(duì)象庫(kù)Excel9.olb.本例也只是對(duì)這個(gè)東東做一個(gè)簡(jiǎn)單的操作了解。有告誡待于朋友們的具體了解:)也算是為我們站點(diǎn)上天天為Excel煩的兄弟們,指一條“明路”吧:)
首先的一步就是使用Tlbimp這個(gè)工具將Excel9.0的對(duì)象庫(kù)文件Excel8.olb轉(zhuǎn)換成為dll,這樣才能做為.Net平臺(tái)Assembly來(lái)使用:)操作如下:
TlbImp Excel9.olb Excel.dll
只要有了這個(gè)Excel.dll,現(xiàn)在我們就能使用Excel的各種操作函數(shù)了。
下面就讓我們具體看看C#是如何使用這些東東吧。
1. 創(chuàng)建一個(gè)新Excel的Application:
Application exc = new Application();
if (exc == null) {
Console.WriteLine("ERROR: EXCEL couldn't be started");
return 0;
}
2. 讓這個(gè)工程可見(jiàn):
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. 給單元格設(shè)置變量:
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;
}
}
現(xiàn)在我們來(lái)看看如何使用數(shù)組,他有些類(lèi)似于設(shè)置單元格。僅僅需要的改變只是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這個(gè)工具的使用啊:)這個(gè)東東很有用,可以將普通Win32程序移植到.Net下面來(lái):)