【发布时间】:2017-03-27 09:17:03
【问题描述】:
我正在尝试在我的 MVC 项目中保存从 excel 阅读器创建的 html 表。 这是上传excel并在浏览器的HTML表格中显示的代码:
上传功能:
public ActionResult Upload()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
// ExcelDataReader works with the binary Excel file, so it needs a FileStream
// to get started. This is how we avoid dependencies on ACE or Interop:
Stream stream = upload.InputStream;
// We return the interface, so that
IExcelDataReader reader = null;
if (upload.FileName.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (upload.FileName.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
else
{
ModelState.AddModelError("File", "This file format is not supported");
return View();
}
reader.IsFirstRowAsColumnNames = true;
DataSet result = reader.AsDataSet();
reader.Close();
return View(result.Tables[0]);
}
else
{
ModelState.AddModelError("File", "Please Upload Your file");
}
}
return View();
}
这是我的查看代码:
@model System.Data.DataTable
@using System.Data;
<h2>Upload File</h2>
@using (Html.BeginForm("Upload", "ImportData", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<div class="form-group">
<input type="file" id="dataFile" name="upload" />
</div>
<div class="form-group">
<input type="submit" value="Upload" class="btn btn-default" />
</div>
if (Model != null)
{
<table>
<thead>
<tr>
@foreach (DataColumn col in Model.Columns)
{
<th>@col.ColumnName</th>
}
</tr>
</thead>
<tbody>
@foreach (DataRow row in Model.Rows)
{
<tr>
@foreach (DataColumn col in Model.Columns)
{
<td>@row[col.ColumnName]</td>
}
</tr>
}
</tbody>
</table>
}
}
使用前面的代码后,html 将在视图中浏览,如下图所示:
最后,我需要将这个 HTML 表格另存为一个新表格:
CREATE TABLE ExcelSheet_name(
ID varchar(50),
FirstName varchar(50),
LastName varchar(50),
.....
XColumn varchar(50));
表格名称取决于excel表格名称,列将取决于HTML表格中显示的列
【问题讨论】:
标签: html sql-server asp.net-mvc razor