所有
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);
C#
中使用
Excel
在做一个小项目,需要把一些查询结果导出到
Excel
,找了一些资料,自己也总结出了一点方法,与大家共享。
一、首先简要描述一下如何操作
Excel
表
先要添加对
Excel
的引用。选择项目
-
〉添加引用
-
〉
COM-
〉添加
Microsoft Excel 9.0
。(不同的
office
讲会有不同版本的
dll
文件)。
using Excel;
using System.Reflection;
//
产生一个
Excel.Application
的新进程
Excel.Application app = new Excel.Application();
if (app == null)
{
statusBar1.Text = "ERROR: EXCEL couldn''''t be started!";
return ;
}
app.Visible = true; //
如果只想用程序控制该
excel
而不想让用户操作时候,可以设置为
false
app.UserControl = true;
Workbooks workbooks =app.Workbooks;
_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet); //
根据模板产生新的
workbook
// _Workbook workbook = workbooks.Add("c://a.xls"); //
或者根据绝对路径打开工作簿文件
a.xls
Sheets sheets = workbook.Worksheets;
_Worksheet worksheet = (_Worksheet) sheets.get_Item(1);
if (worksheet == null)
{
statusBar1.Text = "ERROR: worksheet == null";
return;
}
// This paragraph puts the value 5 to the cell G1
Range range1 = worksheet.get_Range("A1", Missing.Value);
if (range1 == null)
{
statusBar1.Text = "ERROR: range == null";
return;
}
const int nCells = 2345;
range1.Value2 = nCells;
二、示例程序
在
Visual Studio .NET
中建立一个
C# WinForm
工程
.
添加
Microsoft Excel Object Library
引用
:
右键单击
Project ,
选
“
添加引用
”
在
COM
标签项,选中
locate Microsoft Excel Object Library
点确定按钮完成添加引用。
On the View menu, select Toolbox to display the Toolbox. Add two buttons and a check box to Form1.
在
Form1
上添加一个
button1
,双击
Button1
,添加
click
事件的代码
.
把数组里的数据填到
Excel
表格。
首先添加引用:
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
声明两个类的成员变量
Excel.Application objApp;
Excel._Workbook objBook;
private void button1_Click(object sender, System.EventArgs e)
{
Excel.Workbooks objBooks;
Excel.Sheets objSheets;
Excel._Worksheet objSheet;
Excel.Range range;
try
{
// Instantiate Excel and start a new workbook.
objApp = new Excel.Application();
objBooks = objApp.Workbooks;
objBook = objBooks.Add( Missing.Value );
objSheets = objBook.Worksheets;
objSheet = (Excel._Worksheet)objSheets.get_Item(1);
//Get the range where the starting cell has the address
//m_sStartingCell and its dimensions are m_iNumRows x m_iNumCols.
range = objSheet.get_Range("A1", Missing.Value);
range = range.get_Resize(5, 5);
if (this.FillWithStrings.Checked == false)
{
//Create an array.
double[,] saRet = new double[5, 5];
//Fill the array.
for (long iRow = 0; iRow < 5; iRow++)
{
for (long iCol = 0; iCol < 5; iCol++)
{
//Put a counter in the cell.
saRet[iRow, iCol] = iRow * iCol;
}
}
//Set the range value to the array.
range.set_Value(Missing.Value, saRet );
}
else
{
//Create an array.
string[,] saRet = new string[5, 5];
//Fill the array.
for (long iRow = 0; iRow < 5; iRow++)
{
for (long iCol = 0; iCol < 5; iCol++)
{
//Put the row and column address in the cell.
saRet[iRow, iCol] = iRow.ToString() + "|" + iCol.ToString();
}
}
//Set the range value to the array.
range.set_Value(Missing.Value, saRet );
}
//Return control of Excel to the user.
objApp.Visible = true;
objApp.UserControl = true;
}
catch( Exception theException )
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat( errorMessage, theException.Message );
errorMessage = String.Concat( errorMessage, " Line: " );
errorMessage = String.Concat( errorMessage, theException.Source );
MessageBox.Show( errorMessage, "Error" );
}
}
4.
在
Form1
上添加一个
Button2
,双击
Button2
,添加
click
事件的代码,从
Excel
表格读数据到数组
:
private void button2_Click(object sender, System.EventArgs e)
{
Excel.Sheets objSheets;
Excel._Worksheet objSheet;
Excel.Range range;
try
{
try
{
//Get a reference to the first sheet of the workbook.
objSheets = objBook.Worksheets;
objSheet = (Excel._Worksheet)objSheets.get_Item(1);
}
catch( Exception theException )
{
String errorMessage;
errorMessage = "Can''t find the Excel workbook. Try clicking Button1 " +
"to create an Excel workbook with data before running Button2.";
MessageBox.Show( errorMessage, "Missing Workbook?");
//You can''t automate Excel if you can''t find the data you created, so
//leave the subroutine.
return;
}
//Get a range of data.
range = objSheet.get_Range("A1", "E5");
//Retrieve the data from the range.
Object[,] saRet;
saRet = (System.Object[,])range.get_Value( Missing.Value );
//Determine the dimensions of the array.
long iRows;
long iCols;
iRows = saRet.GetUpperBound(0);
iCols = saRet.GetUpperBound(1);
//Build a string that contains the data of the array.
String valueString;
valueString = "Array Data/n";
for (long rowCounter = 1; rowCounter <= iRows; rowCounter++)
{
for (long colCounter = 1; colCounter <= iCols; colCounter++)
{
//Write the next value into the string.
valueString = String.Concat(valueString,
saRet[rowCounter, colCounter].ToString() + ", ");
}
//Write in a new line.
valueString = String.Concat(valueString, "/n");
}
//Report the value of the array.
MessageBox.Show(valueString, "Array Values");
}
catch( Exception theException )
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat( errorMessage, theException.Message );
errorMessage = String.Concat( errorMessage, " Line: " );
errorMessage = String.Concat( errorMessage, theException.Source );
MessageBox.Show( errorMessage, "Error" );
}
}
三、更多内容
《
HOW TO: Transfer Data to an Excel Workbook by Using Visual C# .NET
》描述了多种方式(如数组、数据集、
ADO.NET
、
XML
)把数据导到
Excel
表格的方法。
如果你需要把大数据量倒入到
Excel
表的话,建议使用
ClipBoard(
剪贴板
)
的方法。实现方法参看上面的连接,讨论参看:
http://expert.csdn.net/Expert/topic/3086/3086690.xml
倒完数据后,在程序退出之前,如果需要结束
Excel
的进程,讨论参看:
http://expert.csdn.net/Expert/topic/3068/3068466.xml
讨论的结果就是:提前垃圾回收,或者杀死进程。