分享
 
 
 

C#中使用Excel

王朝c#·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

在做一个小项目,需要把一些查询结果导出到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

讨论的结果就是:提前垃圾回收,或者杀死进程。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有