.net 匯入Excel

來源:互聯網
上載者:User

標籤:

今天我在做匯入Excel的時候遇到了一些問題,順便說句其實我很少做這方面的!我的需求是匯入EXCEL 驗證資料正確性 並把資料顯示到頁面 如有錯誤資訊則彈出來

那具體問題是什麼呢?

匯入Excel有2種方式 各有千秋 根據自己需要決定

第一種:直接就是頁面後台寫代碼,很容易實現。 缺點是:頁面要重新整理並且彈出框只能用系統內建的 所有我採取了第二種方式

頁面代碼:

<form id="formData" enctype="multipart/form-data" method="post" name="files[]" action="/Handler/TestHandler.ashx" target="hidden_frame">

<asp:FileUpload ID="fileSelect" runat="server" />
<asp:Button ID="btnRead" runat="server" Text="匯入EXCEL" OnClick="btnRead_Click" />

</div>
<div id="ListInfo" runat="server"></div>

</from>

後台代碼:

///<summary>
///上傳檔案到臨時目錄中
///</ummary>
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); //擷取檔案的副檔名
if (this.currFileExtension.ToLower() == ".xls" || this.currFileExtension.ToLower() == ".xlsx")
{
this.currFilePath = tempPath + fileName; //擷取上傳後的檔案路徑 記錄到前面聲明的全域變數
file.SaveAs(this.currFilePath); //上傳
}
else
{
throw new Exception("你選擇的檔案格式不正確,只能匯入EXCEL檔案!");
}

}

 

///<summary>
///讀取xls\xlsx格式的Excel檔案的方法
///</ummary>
///<param name="path">待讀取Excel的全路徑</param>
///<returns></returns>
private DataTable ReadExcelToTable(string path, string FileExtension)
{
string connstring = String.Empty;
//連接字串
if (FileExtension == ".xlsx")
{
connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=‘Excel 8.0;HDR=NO;IMEX=1‘;"; // Office 07及以上版本 不能出現多餘的空格 而且分號注意

}
else
{
connstring = " Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + ";Extended Properties=‘Excel 8.0;HDR=Yes;IMEX=1‘;"; //Office 07以下版本
}

using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); //得到所有sheet的名字
string firstSheetName = sheetsName.Rows[0][2].ToString(); //得到第一個sheet的名字
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>
/// 按鈕單擊事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnRead_Click(object sender, EventArgs e)
{

Upload(); //上傳檔案方法
if (this.currFileExtension == ".xlsx" || this.currFileExtension == ".xls")
{
DataTable dt = ReadExcelToTable(currFilePath, this.currFileExtension); //讀取Excel檔案(.xls和.xlsx格式)

string list = "<table>";
for (int i = 0; i < dt.Rows.Count; i++)
{
list += "<tr>";

for (int j = 0; j < dt.Columns.Count; j++)
{

var aa = dt.Rows[i][j];
var bb = dt.Rows[i][0];

list += "<td>" + dt.Rows[i][j] + "</td>";

}
list += "</tr>";
}

ListInfo.InnerHtml = list + "</table>";

}

}

 

 

第二種:是走一般處理常式 這樣系統的許可權也好控制一些

我這做這種方法的時候 我學到了另外一個知識點 就是表單提交不重新整理頁面

js代碼:

$(function() {
$("#formData").submit(function () {
return false;//禁止表單提交
});
$("form input[type=‘submit‘]").click(function () {

var url = $(‘form‘).attr(‘action‘); // 取Form中要提交的連結
var param = {}; // 組裝發送參數
param[‘type‘] = $(‘form input[name=type]‘).val();
$.post("/Handler/TestHandler.ashx", param, function (dom) {
$(‘div‘).html(dom);
});
})

});

這種方法雖然可以不重新整理頁面 但是要上傳檔案的話 這種方式是不可行的 

接下來就說點乾貨。以下這種方式是利用iframe完成的 其原理是表單提交 頁面不重新整理 其實重新整理的是iframe  注意標紅部分

頁面代碼:

<form id="formData" enctype="multipart/form-data" method="post" name="files[]" action="/Handler/TestHandler.ashx" target="hidden_frame">

<input type="file" name="fileUp" id="fileUp"/>
<input type="submit" id="btnConfirm" value="匯入Excel"/>
<input type="hidden" name="type" id="type" value="108" />//一般處理常式接受的參數

<iframe name=‘hidden_frame‘ id="hidden_frame"style=‘display:none‘ src="TestExcel.aspx"></iframe>
</form>
<div class="get" id="get">

</div>

後台代碼:

//聲明變數(屬性)
string currFilePath = string.Empty; //待讀取檔案的全路徑
string currFileExtension = string.Empty; //檔案的副檔名

ReadExcelToTable 方法和上面一樣

//上傳檔案

private void Upload(HttpContext context)
{
HttpPostedFile file = context.Request.Files["fileUp"];
string fileName = file.FileName;
string tempPath = System.IO.Path.GetTempPath(); //擷取系統臨時檔案路徑
fileName = System.IO.Path.GetFileName(fileName); //擷取檔案名稱(不帶路徑)
this.currFileExtension = Path.GetExtension(fileName); //擷取檔案的副檔名
if (this.currFileExtension.ToLower() == ".xls" || this.currFileExtension.ToLower() == ".xlsx")
{
this.currFilePath = tempPath + fileName; //擷取上傳後的檔案路徑 記錄到前面聲明的全域變數
file.SaveAs(this.currFilePath); //上傳
}
else
{
throw new Exception("你選擇的檔案格式不正確,只能匯入EXCEL檔案!");
}

}

 

private ResultMessage ShowAlert(HttpContext context)
{
try
{
Upload(context); //上傳檔案方法
if (this.currFileExtension == ".xlsx" || this.currFileExtension == ".xls")
{
System.Data.DataTable dt = ReadExcelToTable(currFilePath, this.currFileExtension); //讀取Excel檔案(.xls和.xlsx格式)
string list = "<table>";
for (int i = 0; i < dt.Rows.Count; i++)
{
list += "<tr>";

for (int j = 0; j < dt.Columns.Count; j++)
{

var aa = dt.Rows[i][j];
var bb = dt.Rows[i][0];
if (i != 0)
{

list += "<td>" + dt.Rows[i][j] + "</td>";

}
list += "</tr>";
}

var ListInfo = list + "</table>";

//你可以在上面代碼中修改成自己的需求

 

//上面說到我不想用系統內建的彈窗 那麼我們的資料以及錯誤資訊如何展示到頁面上呢? 請看以下代碼:

if (arr.Count != 0)//錯誤提示的集合
{

string str = string.Join(",", arr);
context.Response.Write("<script>var msg=parent.document.getElementById(‘get‘);msg.innerHTML=‘<font color=red>" + ListInfo+ "</font>‘; parent.aa(‘" + str + "‘);</script>");//只有parent.aa()才能調用到你在頁面上的方法 這個方法我是用來彈出錯誤提示的
return new ResultMessage(false,ListInfo ,1,arr);
}
return new ResultMessage(false);
}
return new ResultMessage(false);
}
catch (Exception ex)
{

return new ResultMessage(false);
}
}

大功告成!小女子不才第一次寫部落格!代碼不周到之處,請指教!其實上面的的代碼 我都是從網上看的 改成了自己需要的,以便往後之需!

 

.net 匯入Excel

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.