页面代码

下载文件:

代码:

后端代码:

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=”;

上传文件:

nuget下载:EPPlus.Core

基本思路:这段日子是经过将页面上传播的文本保留至项目地址里面,再读抽取来,再推断传入ecxel文件的头顶是不是相符供给,切合则写入数据库

 图片 1

代码:

后端代码:

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

*仅作为个人学习记录

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*
*
Website