Display the contents of the Excel file on the page

xiaoxiao2021-03-06  20

The first step is to create an Excel file.

The creation of the Excel file is easy. The key step is to select the content you want to display in the page. Select menu "insert" - "Name" "Definition", enter your name to the current selection area. Here, I named myRange1, which will be used later. After the Excel file is edited, save it to the hard disk. I have saved it here to the root directory of the web server, of course, you can also save any position, but you have to pay attention to do certain modifications in your code.

Step 2, encoding.

Create a new ASP.NET application, in the default WebForm1.aspx, drag and drop a DataGrid control, which will be used to display content in Excel. Open the background encoding file, reference the namespace system.Data.OleDb, because this name is used in the later code. Insert the following code in the Page_Load () event:

//

Create a string variable. "Data Source" is where the .xls file is located

String

StrConnection

=

"

Provider = Microsoft.jet.OleDb.4.0;

"

"

Data Source =

"

Server.mappath (

"

../Exceldata.xls

"

)

"

;

"

"

Extended Properties = Excel 8.0;

"

;

//

Create a connection object

OLEDBCONNECTION OBJCONNECTION

=

New

OLEDBCONNECTION (STRCONNECTION);

//

Create an OLEDBCOMMAND object. MyRange1 is the area name defined in the Excel file

OLEDBCOMMAND OBJCMDSELECT

=

New

OLEDBCommand

"

SELECT * from myRANGE1

"

, objconnection; OLEDBDataAdapter Objadapter

=

New

OLEDBDataAdapter (); DataSet DSExcel

=

New

DataSet ();

//

Open database connection

Objconnection.open (); objadapter.selectCommand

=

Objcmdselect; objadapter.fill (DSExcel)

);

//

Bind data to the DataGrid control

DataGrid1.datasource

=

DSEXCEL.TABLES [

0

] .Default1.databind ();

//

Turn off database connection

ObjConnection.Close ();

转载请注明原文地址:https://www.9cbs.com/read-43789.html

New Post(0)