1.JS
upload.render({
elem: '#print',
accept: 'file',
size: 25600,
url: 'ImportFile',
before: function (obj) {
loadIndex = layer.load(1);
},
done: function (res) {
if (res.code == "0000") {
layer.alert(res.text, { title: '完成', icon: 1 });
InitTable.reload();
} else {
layer.alert(res.text, { title: '错误', icon: 5 });
}
layer.close(loadIndex);
}
});
2.接口
public JObject ImportFile()
{
JObject json = new();
try
{
var file = Request.Form.Files;
var filename = ContentDispositionHeaderValue.Parse(file[0].ContentDisposition).FileName.Trim('"');//文件名
var ext = Path.GetExtension(filename);
if (string.IsNullOrWhiteSpace(filename) || (".xls" != Path.GetExtension(filename) && ".xlsx" != Path.GetExtension(filename)))
{
throw new ArgumentException("当前文件格式不正确,请确保正确的Excel文件格式!");
}
string fileExtension = Path.GetExtension(filename); // 文件扩展名
string saveName = DateTime.Now.ToString("yyyyMMddhhmmss") + fileExtension;//新的文件名
var severPath = Directory.GetCurrentDirectory();
//var severPath = @"c:\";
string savePath = Path.Combine(severPath, "wwwroot\\SaveFile");
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
string FileFullName = Path.Combine(savePath, saveName);
using (FileStream fs = System.IO.File.Create(FileFullName))
{
file[0].CopyTo(fs);
fs.Flush();
}
if (!System.IO.File.Exists(FileFullName))
{
json.Add("code", "1001");
json.Add("text", "上传目标失败");
}
else
{
DataTable dt = ExcelHelp.ExcelToTable(FileFullName, "XX表");
if (dt == null || dt.Rows.Count == 0)
{
json.Add("code", "1002");
json.Add("text", "数据为空");
}
else
{
List<CustomsBill> bList = new();
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
var bill = new CustomsBill();
bill.BillNumber = dr["表头"].ToString();
bill.SysID = Guid.NewGuid().ToString("N");
bList.Add(bill);
}
conn.CustomsBills.AddRange(bList);
conn.SaveChanges();
json.Add("code", "0000");
json.Add("text", "操作成功");
}
}
}
catch (Exception ex)
{
json.Add("code", "9999");
json.Add("text", ex.Message);
}
return json;
}