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.
  1. .xls format Office 2003 and the older version
  2. .xlsx format Office 2007 and the last version
  3. .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
  1. <div>
  2. <%-- file upload control, using to upload the file which will be read and get file information--%>
  3. <asp:FileUpload ID="fileSelect" runat="server" />
  4. <%-- click this button to run read method--%>
  5. <asp:Button ID="btnRead" runat="server" Text="ReadStart" />
  6. </div>
Background
  1. //Declare Variable (property)
  2. string currFilePath = string.Empty; //File Full Path
  3. string currFileExtension = string.Empty; //File Extension
  4. //Page_Load Event, Register Button Click Event
  5. protected void Page_Load(object sender, EventArgs e) {
  6. this.btnRead.Click += new EventHandler(btnRead_Click);
  7. }
  8. //Button Click Event
  9. protected void btnRead_Click(object sender, EventArgs e) {
  10. Upload(); //Upload File Method
  11. if (this.currFileExtension == ".xlsx" || this.currFileExtension == ".xls") {
  12. DataTable dt = ReadExcelToTable(currFilePath); //Read Excel File (.XLS and .XLSX Format)
  13. } else if (this.currFileExtension == ".csv") {
  14. DataTable dt = ReadExcelWidthStream(currFilePath); //Read .CSV File
  15. }
  16. }
The following shows three methods in button click event.
  1. ///<summary>
  2. ///Upload File to Temporary Category
  3. ///</summary>
  4. private void Upload() {
  5. HttpPostedFile file = this.fileSelect.PostedFile;
  6. string fileName = file.FileName;
  7. string tempPath = System.IO.Path.GetTempPath(); //Get Temporary File Path
  8. fileName = System.IO.Path.GetFileName(fileName); //Get File Name (not including path)
  9. this.currFileExtension = System.IO.Path.GetExtension(fileName); //Get File Extension
  10. this.currFilePath = tempPath + fileName; //Get File Path after Uploading and Record to Former Declared Global Variable
  11. file.SaveAs(this.currFilePath); //Upload
  12. }
  13. ///<summary>
  14. ///Method to Read XLS/XLSX File
  15. ///</summary>
  16. ///<param name="path">Excel File Full Path</param>
  17. ///<returns></returns>
  18. private DataTable ReadExcelToTable(string path) {
  19. //Connection String
  20. string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; // Extra blank space cannot appear in Office 2007 and the last version. And we need to pay attention on semicolon.
  21. string connstring = Provider = Microsoft.JET.OLEDB .4 .0;
  22. Data Source = " + path + ";
  23. Extended Properties = " 'Excel 8.0;HDR=NO;IMEX=1';"; //This connection string is appropriate for Office 2007 and the older version. We can select the most suitable connection string according to Office version or our program.
  24. using(OleDbConnection conn = new OleDbConnection(connstring)) {
  25. conn.Open();
  26. DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); //Get All Sheets Name
  27. string firstSheetName = sheetsName.Rows[0][2].ToString(); //Get the First Sheet Name
  28. string sql = string.Format("SELECT * FROM [{0}],firstSheetName"); //Query String
  29. OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring);
  30. DataSet set = new DataSet();
  31. ada.Fill(set);
  32. return set.Tables[0];
  33. }
  34. }
  35. ///<summary>
  36. ///Method to Read CSV Format
  37. ///</summary>
  38. ///<param name="path">Read File Full Path</param>
  39. ///<returns></returns>
  40. private DataTable ReadExcelWithStream(string path) {
  41. DataTable dt = new DataTable();
  42. bool isDtHasColumn = false; //Mark if DataTable Generates Column
  43. StreamReader reader = new StreamReader(path, System.Text.Encoding.Default); //Data Stream
  44. while (!reader.EndOfStream) {
  45. string meaage = reader.ReadLine();
  46. string[] splitResult = message.Split(new char[] { ',' }, StringSplitOption.None); //Read One Row and Separate by Comma, Save to Array
  47. DataRow row = dt.NewRow();
  48. for (int i = 0; i < splitResult.Length; i++) {
  49. if (!isDtHasColumn) //If not Generate Column
  50. {
  51. dt.Columns.Add("column" + i, typeof(string));
  52. }
  53. row[i] = splitResult[i];
  54. }
  55. dt.Rows.Add(row); //Add Row
  56. isDtHasColumn = true; //Mark the Existed Column after Read the First Row, Not Generate Column after Reading Later Rows
  57. }
  58. return dt;
  59. }

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