ASP.NET of C reads the contents of Excel files

  • 2020-05-26 08:17:18
  • OfStack

.xls format Office2003 and below
.xlsx format Office2007 and above
.csv comma delimited string text (you can save the above two file types in this format)
There are two different ways to read the first two formats and the second one.

Here's the program:
Page foreground:


<div>       <%--  File upload control    Used for uploading files to 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:


 // Declare variables (properties) 
 string currFilePath = string.Empty; // The full path of the file to be read  
 string currFileExtension = string.Empty;  // The extension of the file  

 //Page_Load The event   Register button click events  
 protected void Page_Load(object sender,EventArgs e) 
 { 
     this.btnRead.Click += new EventHandler(btnRead_Click); 
 }

 
 // Button click event    // The inside of the 3 Three methods are given below 
 protected void btnRead_Click(object sender,EventArgs e)
 {
     Upload();  // Upload file method 
     if(this.currFileExtension ==".xlsx" || this.currFileExtension ==".xls")
       {
            DataTable dt = ReadExcelToTable(currFilePath);  // read Excel File ( .xls and .xlsx Format) 
       }
       else if(this.currFileExtension == ".csv")
         {
               DataTable dt = ReadExcelWidthStream(currFilePath);  // read .csv Format file 
         }
 }

The three methods in the button click event are listed below


///<summary>
/// Upload files to a temporary directory  
///</ummary>
private void Upload()
{
HttpPostedFile file = this.fileSelect.PostedFile;
string fileName = file.FileName;
string tempPath = System.IO.Path.GetTempPath(); // Gets the system temporary file path 
fileName = System.IO.Path.GetFileName(fileName); // Get file name (without path) 
this.currFileExtension = System.IO.Path.GetExtension(fileName); // Gets the extension of the file 
this.currFilePath = tempPath + fileName; // Gets the path to the uploaded file   Log to the previously declared global variable 
file.SaveAs(this.currFilePath); // upload 
}

///<summary>
/// read xls\xlsx The format of Excel File method  
///</ummary>
///<param name="path"> To be read Excel The full path of </param>
///<returns></returns>
private DataTable ReadExcelToTable(string path)
{
// Concatenation string 
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; // Office 07 Version and above   No extra Spaces are allowed   And notice the semicolon 
//string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; //Office 07 The following version   Because I use Office2010  So this connection string is not used   You can choose according to your own situation   Or the program decides what to use 1 Connection string 
using(OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"Table"}); // Get all the sheet The name of the 
string firstSheetName = sheetsName.Rows[0][2].ToString(); // Get the first 1 a sheet The name of the 
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 csv The format of Excel File method  
///</ummary>
///<param name="path"> To be read Excel The full path of </param>
///<returns></returns>
private DataTable ReadExcelWithStream(string path)
{
DataTable dt = new DataTable();
bool isDtHasColumn = false; // tag DataTable  Whether a column has been generated 
StreamReader reader = new StreamReader(path,System.Text.Encoding.Default); // The data flow 
while(!reader.EndOfStream)
{
string meaage = reader.ReadLine();
string[] splitResult = message.Split(new char[]{','},StringSplitOption.None); // read 1 line   Separated by commas   Deposited in the array 
DataRow row = dt.NewRow();
for(int i = 0;i<splitResult.Length;i++)
{
if(!isDtHasColumn) // If the column has not been generated 
{
dt.Columns.Add("column" + i,typeof(string));
}
row[i] = splitResult[i];
}
dt.Rows.Add(row); // Add the line 
isDtHasColumn = true; // Read the first 1 After the line   The tag already exists in the column   Columns are no longer generated when subsequent rows are read 
}
return dt;
}


Related articles: