C#教程之asp.net core 下载文件,上传excel文件
https://www.xin3721.com/Python/python13673.html
下载文件:
代码:
后端代码:
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
*仅作为个人学习记录
标签:files,文件,asp,string,core,worksheet,colName,new From: https://www.cnblogs.com/sunny3158/p/17033819.html