技術(shù)頻道導(dǎo)航
HTML/CSS
.NET技術(shù)
IIS技術(shù)
PHP技術(shù)
Js/JQuery
Photoshop
Fireworks
服務(wù)器技術(shù)
操作系統(tǒng)
網(wǎng)站運(yùn)營

贊助商

分類目錄

贊助商

最新文章

搜索

C# .NET訪問OLEDB或StreamReader讀取Excel(.xls/.xlsx/.csv)文件

作者:admin    時(shí)間:2023-5-23 14:32:13    瀏覽:

Excel 文件分為三種類型:

  • .xls 格式 Office 2003 及舊版本
  • .xlsx 格式 Office 2007 及最新版本
  • .csv 格式 String 文本,以逗號(hào)分隔(以上兩種格式都可以另存為這種格式。)

我們需要使用不同的方式來讀取第一格式文件、第二格式文件和第三格式文件。

在本文中,我將展示一種使用 .NET 讀取 Excel 文件內(nèi)容的方法。

HTML代碼

<div>  
       <%-- 文件上傳控件,用于上傳要讀取的文件,獲取文件信息 --%>  
       <asp:FileUpload ID="fileSelect" runat="server" />    
       <%-- 點(diǎn)擊這個(gè)按鈕運(yùn)行讀取方法 --%>  
       <asp:Button ID="btnRead" runat="server" Text="ReadStart" />  
</div> 

后臺(tái)代碼

//聲明變量(屬性)  
string currFilePath = string.Empty; //文件全路徑  
string currFileExtension = string.Empty; //文件擴(kuò)展名  
  
//Page_Load事件,注冊(cè)按鈕點(diǎn)擊事件  
protected void Page_Load(object sender, EventArgs e) {  
  this.btnRead.Click += new EventHandler(btnRead_Click);  
}  
  
//按鈕點(diǎn)擊事件   
protected void btnRead_Click(object sender, EventArgs e) {  
  Upload(); //上傳文件方法  
  if (this.currFileExtension == ".xlsx" || this.currFileExtension == ".xls") {  
    DataTable dt = ReadExcelToTable(currFilePath); //讀取Excel文件(.XLS 和 .XLSX 格式)  
  } else if (this.currFileExtension == ".csv") {  
    DataTable dt = ReadExcelWidthStream(currFilePath); //讀取 .CSV 文件  
  }  

下面展示了按鈕點(diǎn)擊事件中的三個(gè)方法。

///<summary>  
///上傳文件到臨時(shí)目錄  
///</summary>  
private void Upload() {  
  HttpPostedFile file = this.fileSelect.PostedFile;  
  string fileName = file.FileName;  
  string tempPath = System.IO.Path.GetTempPath(); //獲取臨時(shí)文件路徑  
  fileName = System.IO.Path.GetFileName(fileName); //獲取文件名(不包括路徑)  
  this.currFileExtension = System.IO.Path.GetExtension(fileName); //獲取文件擴(kuò)展名  
  this.currFilePath = tempPath + fileName; //獲取上傳后的文件路徑記錄到之前聲明的全局變量中  
  file.SaveAs(this.currFilePath); //上傳 
}  
  
///<summary>  
///讀取 XLS/XLSX 文件的方法  
///</summary>
///<param name="path">Excel文件完整路徑</param>  
///<returns></returns>  
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';"; // Office 2007及上一版本不能出現(xiàn)多余的空格。我們需要注意分號(hào)。  
  string connstring = Provider = Microsoft.JET.OLEDB .4 .0;  
  Data Source = " + path + ";  
  Extended Properties = " 'Excel 8.0;HDR=NO;IMEX=1';"; //此連接字符串適用于 Office 2007 及舊版本。我們可以根據(jù)Office版本或者我們的程序選擇最合適的連接字符串。  
  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(); //獲取第一個(gè)工作表名稱  
    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];  
  }  
}  
///<summary>  
///讀CSV格式的方法
///</summary>  
///<param name="path">讀取文件完整路徑</param>  
///<returns></returns>  
private DataTable ReadExcelWithStream(string path) {  
  DataTable dt = new DataTable();  
  bool isDtHasColumn = false; //標(biāo)記DataTable是否生成列  
  StreamReader reader = new StreamReader(path, System.Text.Encoding.Default); //數(shù)據(jù)流  
  while (!reader.EndOfStream) {  
    string meaage = reader.ReadLine();  
    string[] splitResult = message.Split(new char[] { ',' }, StringSplitOption.None); //讀取一行并以逗號(hào)分隔,保存到數(shù)組  
    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; //讀取第一行后標(biāo)記已存在的列,讀取后面的行后不生成  
  }  
  return dt;  

總結(jié)

本文僅供參考,方便學(xué)習(xí)。因此,該方法沒有考慮復(fù)雜的情況。如果要讀取稍微復(fù)雜的Excel文件,可以看看下面的方法。

相關(guān)文章

標(biāo)簽: CSharp  asp.net  CSV  Excel  
x
  • 站長推薦
/* 左側(cè)顯示文章內(nèi)容目錄 */