An example of how ASP. NET (C #) reads an Excel file

Source: Internet
Author: User
. xls format Office2003 and the following versions
. xlsx format Office2007 and later
Comma-delimited string literals in the. csv format (you can save both of these file types in this format)
There are two different ways to read the first two formats and to read the latter format.

The following program:
Page Front Desk:

The <div>       <%--file Upload control is  used to upload the file that will be read and get the file information through this control--%>      <asp:fileupload id= "Fileselect" runat= " Server "/>          <%--Click this button to execute the Read method--%>       <asp:button id=" Btnread "runat=" Server "text=" Readstart "/> </div>

Background code:

Declares a variable (property) string Currfilepath = String. Empty; The full path of the file to be read  string currfileextension = string. Empty;  File extension  //page_load Event Registration button Click event  protected void Page_Load (Object Sender,eventargs e)  {      This.btnRead.Click + = new EventHandler (Btnread_click);  }  button click event   //The 3 methods inside will give protected void Btnread_click (Object Sender,eventargs e) {     Upload () below;  Upload File Method     if (this.currfileextension = = ". xlsx" | | this.currfileextension = = ". xls")       {            DataTable dt = Readexceltotable (Currfilepath);  Read Excel files (. xls and. xlsx format)       }       else if (this.currfileextension = = ". csv")         {               DataTable dt = Readexcelwidthstream (Currfilepath);  Read. csv format file         }}

The 3 methods in the button click event are listed below

<summary>///upload files to temp directory///</ummary> private void Upload () {Httppostedfile file = This.fileSelect.Pos  Tedfile; String fileName = file.  FileName; String temppath = System.IO.Path.GetTempPath (); Gets the system temp file path filename = System.IO.Path.GetFileName (filename); Get file name (without path) this.currfileextension = System.IO.Path.GetExtension (filename); Get the file extension This.currfilepath = TempPath + fileName; Gets the uploaded file path recorded to the previously declared global variable file. SaveAs (This.currfilepath); Upload}///<summary>////Read XLS\XLSX format Excel file///</ummary>///<param name= "path" > Full path for Excel to be read    Path </param>///<returns></returns> Private DataTable readexceltotable (string path) {//connection string String connstring = "Provider=microsoft.ace.oledb.12.0;data source=" + path + "; Extended properties= ' Excel 8.0; Hdr=no;imex=1 '; "; Office 07 and later versions cannot appear with extra spaces and semicolons Note//string connstring = Provider=Microsoft.Jet.OLEDB.4.0;Data source= "+ path +"; Extended properties= ' Excel 8.0; Hdr=no;iMex=1 '; "; The following versions of Office 07 do not use this connection string because I use Office2010 to choose which connection string to use (OleDbConnection conn = new Oledbconnect, depending on your situation). Ion (ConnString)) {Conn.    Open (); DataTable sheetsname = conn. GetOleDbSchemaTable (Oledbschemaguid.tables,new object[]{null,null,null, "Table"}); Get the name of all sheet string firstsheetname = sheetsname.rows[0][2]. ToString (); Get the first sheet name string sql = string. Format ("select * from [{0}],firstsheetname)";    Query string OleDbDataAdapter ada =new OleDbDataAdapter (sql,connstring);    DataSet set = new DataSet (); Ada.    Fill (set); return set.    Tables[0]; }}///<summary>////Read the CSV format of Excel file///</ummary>///<param name= "path" > to be read by Excel      Full path </param>///<returns></returns> private DataTable Readexcelwithstream (string path) {      DataTable dt = new DataTable (); BOOL Isdthascolumn = false; Mark whether the DataTable has generated columns StreamReader reader = new StreamReader (path,system.text.encoding.default); Data flow while (!reader. Endofstream) {String meaage = reader.      ReadLine (); string[] Splitresult = message. Split (New char[]{', '},stringsplitoption.none); Reads a row with a comma-delimited array of DataRow row = dt.      NewRow (); for (int i = 0;i<splitresult.length;i++) {if (!isdthascolumn)//If the column {DT has not yet been generated.      Columns.Add ("column" + i,typeof (string));      } Row[i] = Splitresult[i]; } dt. Rows.Add (row); Add row Isdthascolumn = true;      Columns are no longer generated after the first line is read and the row is marked for the existing column before it is read. }


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.