Visual C # programming Excel

Source: Internet
Author: User
Abstract: This article introduces the Excel objects and the Managed Objects in C #. Code And non-managed code, and introduces the use of COM components in the. NET environment.

Keywords:Managed code; unmanaged code; EXCEL object; Dynamic Connection Library

Introduction

Excel is a software in Microsoft Office Automation suite. It is mainly used to process workbooks. Excel has been welcomed by many users for its powerful functions and friendly interfaces. When designing an application system, different users have different requirements for printing.ProgramThe print function in is suitable for every user. it is conceivable that the program design is very complicated. Because the Excel table is powerful, and almost every machine has installed it, if you put the results of program processing in the Excel table, in this way, each user can customize their own printing in EXCEL according to their own needs. This not only makes the program design simple, but also meets the requirements of many users and is more practical. So how can I use Visual C # To Call Excel and store data in an Excel table? This article will discuss the solutions to the above problems.

Excel objects

Microsoft's EXCEL object model contains 128 different objects, from simple objects such as Rectangles and text boxes to complex objects such as pivot tables and charts. next, we will briefly introduce the most important and most commonly used four objects.

(1) Application object. The application object is at the top level of the Excel object hierarchy, indicating the Excel running environment.

(2) workbook object. The workbook object is directly in the lower layer of the Application object, indicating an Excel worksheet file.

(3) worksheet object. The Worksheet object is included in the workbook object, indicating an Excel worksheet.

(4) range object. The range object contains the worksheet object, which indicates one or more cells in an Excel worksheet.

Managed code and unmanaged code in C #

Programs running in the. net public language framework are managed code. All types of managed code in the program are strictly checked, with no pointers. The management of memory is completely controlled by the operating system. Under control, programming is easier and less error-prone, so we can spend more time solving practical problems rather than computer language problems. Relatively speaking, programs running outside the. NET Framework are unmanaged code. For example, COM components, ActiveX components, Win32 API functions, and pointer operations. C # in programming, you must use unmanaged code in certain situations. For example, you must use a mature COM component or call an API function, or use pointers to write real-time/efficient programs.

Call the Excel COM component in Visual C #

One. NET component is actually.. Net DLL, which contains not only the running program itself, but also the description of the DLL (meta data, that is, metadata ), a com component uses its class library (TLB) to store its description information. These COM components are not managed code. To use these COM components in Visual C #, you must convert them into managed code. NET components. Therefore, before using Visual C # to call an Excel table, you must complete the conversion from the unmanaged code of the COM component to the class library of the managed code.

1. Convert the COM component of EXCEL to the. NET component.

Open the Add reference dialog box in the project, select the com column, and find "Microsoft Excel 9.0 Object Library" (Office 2000) in the com list ), add it to the project references. Visual C #. Net automatically generates the corresponding. NET component file.

This conversion form. the. NET component cannot be used independently. It is only an outer package of the previous COM component. net, you can use this outer package to find the original COM component and call its corresponding interface functions. Therefore, it must work with the original COM component.

2. Visual C # open an Excel table

In fact, using a converted COM component in C # is exactly the same as using any other. NET component. You can use the new keyword to create a converted COM component and then use the component object like any other C # object.

After conversion. the. NET Component defines a namespace excel, which encapsulates a class application. This class has a very important relationship with starting an Excel table. in Visual C, you only need the following three lines of code to open an Excel Worksheet:

Excel. Application Excel = new excel. Application (); // reference an Excel Object
Excel. application. workbooks. Add (true); // reference an Excel Workbook
Excel. Visible = true; // make Excel visible

However, the Excel table is an empty table with no content. The following describes how to input data into the Excel table.

3. input data to an Excel table

In the namespace "Excel", a class "cell" is also defined, which represents a cell in an Excel table. By assigning values to "cell", you can input data to an Excel table. The following code is used to open an Excel table and input some data to the table.

Excel. Application Excel = new excel. Application ();
Excel. application. workbooks. Add (true );
Excel. cells [1, 1] = "First row first column ";
Excel. cells [1, 2] = "First row second column ";
Excel. cells [2, 1] = "second row first column ";
Excel. cells [2, 2] = "second row second column ";
Excel. Visible = true;

4. Instances

The following example connects to the Oracle database (name) in C #, reads data from the table (tablename), and writes data to excel.

String cnstring = "provider = msdaora.1; Data Source = Name ;";
Cnstring = cnstring + "User ID = username; Password = password ";
Try
{
Oledbconnection Cn = new oledbconnection (cnstring );
CN. open ();
Try
{
String S = "select * from name. tablename ";
Oledbcommand cmd = new oledbcommand (S, CN );
Oledbdatareader DR = cmd. executereader ();
Excel. Application xlapp = new excel. Application ();
If (xlapp = NULL) {MessageBox. Show ("can't open excel! "); Return ;}
Xlapp. application. workbooks. Add (true );
Int ROW = 2, fieldcount;
Fieldcount = dr. fieldcount;
For (INT Col = 0; Col <fieldcount; Col ++) xlapp. cells [1, Col + 1] = dr. getname (COL );
While (dr. Read ())
{
For (INT Col = 0; Col <fieldcount; Col ++)
Xlapp. cells [row, Col + 1] = dr. getvalue (COL). tostring ();
Row ++;
}
Xlapp. Visible = true;
Xlapp = NULL;
}
Catch (exception ex) {MessageBox. Show (ex. Message );}
Finally {CN. Close ();}
}
Catch (exception ex) {MessageBox. Show (ex. Message );}
}
}

5. Install A. Net program using the COM component.

If you want to install and run such a program on another machine, in addition to installing and running the program, there are three things to do.

First, install the. NET operating system. Because no. Net program can be run independently from the. NET running system.

Second, the called COM component must be installed on the target machine. In this example, Microsoft Office Excel is installed on most target machines. However, if it is another custom COM component, the COM component must be installed before running the. NET program.

Finally, the converted. NET Component DLL file must be installed on the target machine. Because the. NET component does not need to be registered in Windows Registry, the simplest method is to copy the. NET Component DLL file to the running program directory. If the. NET component is shared by multiple. net programs, you can install it in the. NET public component area to be used by any. NET component. Only when a. NET component is involved in transaction processing, it must be registered as a COM + component. Because. Net still uses the traditional COM + mechanism to handle transaction commit and rollback.

Summary

Through the above discussion, we know how to use the Excel COM component in C. It should be noted that the EXCEL object contains a lot of content that we have not introduced, and we need to continue to learn during use. We also learned how to use COM components in C.

References:

[1] Liu Hongcheng C #2003.7 jobs of Tsinghua University Press for advanced programming 187 ~ 200

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.