Introduction
It is possible that we need to read Excel files when developing. In this article, I will show one method to read Excel file contents with .NET.
As is known, there are three types of Excel file.
- .xls format Office 2003 and the older version
- .xlsx format Office 2007 and the last version
- .csv format String text by separating with comma (the above two format can be saved as this format.)
We need to use different ways to read the first, second format files and the third format files.
Using the Code
Foreground
- <div>
- <%-- file upload control, using to upload the file which will be read and get file information--%>
- <asp:FileUpload ID="fileSelect" runat="server" />
- <%-- click this button to run read method--%>
- <asp:Button ID="btnRead" runat="server" Text="ReadStart" />
- </div>
Background
-
- string currFilePath = string.Empty;
- string currFileExtension = string.Empty;
-
-
- protected void Page_Load(object sender, EventArgs e) {
- this.btnRead.Click += new EventHandler(btnRead_Click);
- }
-
-
- protected void btnRead_Click(object sender, EventArgs e) {
- Upload();
- if (this.currFileExtension == ".xlsx" || this.currFileExtension == ".xls") {
- DataTable dt = ReadExcelToTable(currFilePath);
- } else if (this.currFileExtension == ".csv") {
- DataTable dt = ReadExcelWidthStream(currFilePath);
- }
- }
The following shows three
methods in button click event.
-
-
-
- private void Upload() {
- HttpPostedFile file = this.fileSelect.PostedFile;
- string fileName = file.FileName;
- string tempPath = System.IO.Path.GetTempPath();
- fileName = System.IO.Path.GetFileName(fileName);
- this.currFileExtension = System.IO.Path.GetExtension(fileName);
- this.currFilePath = tempPath + fileName;
- file.SaveAs(this.currFilePath);
- }
-
-
-
-
-
-
- private DataTable ReadExcelToTable(string path) {
-
- string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
- string connstring = Provider = Microsoft.JET.OLEDB .4 .0;
- Data Source = " + path + ";
- Extended Properties = " 'Excel 8.0;HDR=NO;IMEX=1';";
- using(OleDbConnection conn = new OleDbConnection(connstring)) {
- conn.Open();
- DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
- string firstSheetName = sheetsName.Rows[0][2].ToString();
- string sql = string.Format("SELECT * FROM [{0}],firstSheetName");
- OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring);
- DataSet set = new DataSet();
- ada.Fill(set);
- return set.Tables[0];
- }
- }
-
-
-
-
-
- private DataTable ReadExcelWithStream(string path) {
- DataTable dt = new DataTable();
- bool isDtHasColumn = false;
- StreamReader reader = new StreamReader(path, System.Text.Encoding.Default);
- while (!reader.EndOfStream) {
- string meaage = reader.ReadLine();
- string[] splitResult = message.Split(new char[] { ',' }, StringSplitOption.None);
- DataRow row = dt.NewRow();
- for (int i = 0; i < splitResult.Length; i++) {
- if (!isDtHasColumn)
- {
- dt.Columns.Add("column" + i, typeof(string));
- }
- row[i] = splitResult[i];
- }
- dt.Rows.Add(row);
- isDtHasColumn = true;
- }
- return dt;
- }
Conclusion
This article is just used for reference and studying easily. Therefore, there are not complicated situations considered in this method.
In addition, I want to recommand two articles about operating Excel for you.
http://www.codeproject.com/KB/aspnet/coolcode2_aspx.aspx
http://www.codeproject.com/KB/cs/csharpexcel.aspx