【发布时间】:2021-01-29 10:23:37
【问题描述】:
我正在努力在我的项目中导入 csv 文件。 我想在保存到 sql 数据库之前上传一个 csv 文件并显示数据。 我正在使用 asp .net core razor 页面。 这是我的 C# 导入方法:
public ActionResult OnPostImport()
{
IFormFile file = Request.Form.Files[0];
string folderName = "Upload";
string webRootPath = _hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
StringBuilder sb = new StringBuilder();
if (!Directory.Exists(newPath))
Directory.CreateDirectory(newPath);
if (file.Length > 0)
{
string sFileExtension = Path.GetExtension(file.FileName).ToLower();
ISheet sheet;
string fullPath = Path.Combine(newPath, file.FileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
stream.Position = 0;
if (sFileExtension == ".xls")//This will read the Excel 97-2000 formats
{
HSSFWorkbook hssfwb = new HSSFWorkbook(stream);
sheet = hssfwb.GetSheetAt(0);
}
else //This will read 2007 Excel format
{
XSSFWorkbook hssfwb = new XSSFWorkbook(stream);
sheet = hssfwb.GetSheetAt(0);
}
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
// Start creating the html which would be displayed in tabular format on the screen
sb.Append("<table class='table'><tr>");
for (int j = 0; j < cellCount; j++)
{
NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j);
if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue;
sb.Append("<th>" + cell.ToString() + "</th>");
}
sb.Append("</tr>");
sb.AppendLine("<tr>");
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
sb.Append("<td>" + row.GetCell(j).ToString() + "</td>");
}
sb.AppendLine("</tr>");
}
sb.Append("</table>");
}
}
return this.Content(sb.ToString());
}
这是我的前端代码:
<h2>Import</h2>
<br />
<form method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-4">
<input type="file" id="fUpload" name="files" class="form-control" />
</div>
<div class="col-md-8">
<input type="button" id="btnUpload" value="Upload" />
</div>
</div>
<br />
<div id="dvData"></div>
</form>
Javascript 代码:
@Html.AntiForgeryToken()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script>
$(function () {
$('#btnUpload').on('click', function () {
var fileExtension = ['xls', 'xlsx'];
var filename = $('#fUpload').val();
if (filename.length === 0) {
alert("Please select a file.");
return false;
}
else {
var extension = filename.replace(/^.*\./, '');
if ($.inArray(extension, fileExtension) === -1) {
alert("Please select only excel files.");
return false;
}
}
var fdata = new FormData();
var fileUpload = $("#fUpload").get(0);
var files = fileUpload.files;
fdata.append(files[0].name, files[0]);
$.ajax({
type: "POST",
url: "/Home/ImportCSVFile?handler=ImportFromExcel",
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: fdata,
contentType: false,
processData: false,
success: function (response) {
if (response.length === 0)
alert('Some error occured while uploading');
else {
$('#dvData').html(response);
}
},
error: function (e) {
$('#dvData').html(e.responseText);
}
});
});
});
</script>
他们的 ajax 调用没有到达 c# 方法。请帮助我不确定我在上面的代码中遗漏了什么。还请告知我如何在导入 csv 文件后将数据保存到 sql。
【问题讨论】:
标签: javascript html ajax asp.net-core