下載文件: 代碼: 後端代碼: public IActionResult DownloadFile() { var FilePath = @"./files/deparment.xlsx"; var stream = System.IO.File.OpenRead(FilePath); return ...
下載文件:
代碼:
後端代碼:
public IActionResult DownloadFile()
{
var FilePath = @"./files/deparment.xlsx";
var stream = System.IO.File.OpenRead(FilePath);
return File(stream, "application/vnd.android.package-archive", Path.GetFileName(FilePath));
}
頁面代碼:
<a href="http://****/DownloadFile">下載</a>
上傳文件:
nuget下載:EPPlus.Core
基本思路:目前是通過將頁面上傳入的文件保存至項目地址裡面,再讀取出來,再判斷傳入ecxel文件的頭部是否符合要求,符合則寫入資料庫
代碼:
後端代碼:
public object AddMulitDeparment(IFormCollection files)
{
string[] colName = new string[] { "公司名稱", "部門經理", "部門名稱", "員工數量", "部門代碼" };
var result = new object();
string message = "";
if (files != null && files.Files.Count > 0)
{
for (int i = 0; i < files.Files.Count; i++)
{
var file = files.Files[i];
try
{
object path = _importExcelUtil.SaveExcel(file);
FileInfo fileInfo = new FileInfo((string)path);
using (FileStream fs = new FileStream(fileInfo.ToString(), FileMode.Create))
{
file.CopyTo(fs);
fs.Flush();
}
using (ExcelPackage package = new ExcelPackage(fileInfo))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
if (_importExcelUtil.JudgeCol(worksheet,colName))
{
result = new
{
data = _importExcelUtil.SaveDepToDB(worksheet)
};
System.IO.File.Delete((string)path);
}
}
}
catch (Exception ex)
{
message= ex.Message;
}
}
}
return result;
}
//判斷頭部(取出表格內容同)
public bool JudgeCol(ExcelWorksheet worksheet,string[] colName)
{
int ColCount = worksheet.Dimension.Columns;
bool bHeaderRow = true;
//excel下標從1開始
for (int col = 1,index=0; col <= ColCount&&index<colName.Length; col++,index++)
{
string c = worksheet.Cells[1, col].Value.ToString();
if (!c.Equals(colName[index]))
{
bHeaderRow = false;
throw new Exception("格式錯誤,導入文件的第"+index+"列應為"+colName[index]+"!");
}
}
return bHeaderRow;
}
前端代碼,由於需要上傳文件,需要將http請求頭部的Content-Type修改為multipart/form-data
*僅作為個人學習記錄