Excel的下載和讀取,部分代碼(大神請路過)
A.下載Excel表或其他文件(運用瀏覽器自帶的功能實現下載)
a) 前臺頁面:
<a href="/SolidTransfers/DownloadFile" class="btn" >下載模板</a>
b) 後臺方法:
public ActionResult DownloadFile()
{
var path = Server.MapPath("~/App_Data/OAupload/TempExcel/文件名.xlsx");
var name = Path.GetFileName(path);
string fileName = DateTime.Now.ToString("yyyyMMddmmss") + name;
return File(path, "application/zip-x-compressed", fileName);
}
B.讀取Excel表
a) 前臺頁面:
//action:路由規則,enctype:上傳文件的格式(固定),method:文件的提交方式
<form action="/SolidTransfers/ExcelWrite" enctype="multipart/form-data" method="post" target="iframe">
<h5>請上傳.xlsx文件</h5>
<input type="file" name="file" id="file" />
<input type="submit" class="btn" value="提交文件" style="float: right;">
//iframe作用:提交表單完成後不刷新頁面,加載iframe的內容,這裏用來阻止 頁面的跳轉
<iframe name="iframe" id="iframe" style="display: none" onload="Show()"></iframe>
</form>
b) 後臺方法:
[HttpPost]//規定提交文件的方式
public void ExcelWrite()
{
try
{
HttpFileCollectionBase fileCollection = Request.Files;
if (fileCollection.Count > 0)
{
HttpPostedFileBase postedFile = fileCollection[0];
string fileFolderPath = Request.MapPath("/App_Data/SolidExcel/OAupload/");
string proID = "PRJ" + DateTime.Now.ToString("yyyyMMddhhmmss");
var fileName = proID + postedFile.FileName;
if (!Directory.Exists(fileFolderPath))
{
Directory.CreateDirectory(fileFolderPath);
}
if (!string.IsNullOrEmpty(postedFile.FileName))
{
postedFile.SaveAs(fileFolderPath + "/" + fileName);
}
FileStream fs = System.IO.File.OpenRead(fileFolderPath + "/" + fileName); //打開myxls.xls文件
XSSFWorkbook wk = new XSSFWorkbook(fs); //把xls文件中的數據寫入 wk中
ISheet sheet = wk.GetSheetAt(0); //讀取當前表數據
List<string> list = new List<string>();
list.Add(sheet.GetRow(0).GetCell(0).ToString()); //突發環境事件應急 預案備案申請表0
list.Add(sheet.GetRow(2).GetCell(1).ToString());//單位名稱1
list.Add(sheet.GetRow(3).GetCell(1).ToString());//法定代表人2
list.Add(sheet.GetRow(4).GetCell(1).ToString());//聯系人3
list.Add(sheet.GetRow(5).GetCell(1).ToString());//傳真4
}
}
catch (Exception ex)
{
}
}
Excel的下載和讀取,部分代碼(大神請路過)