当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net core 下载文件,上传excel文件

asp.net core 下载文件,上传excel文件

2018年09月05日  | 移动技术网IT编程  | 我要评论

高明旅游景点大全,德格拉克,黄蓉h版系列第116部分

下载文件:

代码:

后端代码:

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

*仅作为个人学习记录

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网