Reputation: 5242
My controller:
[HttpPost]
public ActionResult ShowExcelFile(HttpPostedFileBase getFile)
{
//Make something with values of getFile
return PartialView("ShowExcelFile");
}
In my view:
@using (Html.BeginForm("ShowExcelFile", "ShowExcel", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" id="getFile" name="getFile" /><br />
<input type="submit" value="Upload file" />
}
How can I read the values from getFile?
Upvotes: 0
Views: 5923
Reputation: 6832
An easy way to parse an Excel file is to use a library such as Excel Data Reader (available as a Nuget package as well). And once installed, reading your Excel file is quite simple.
using Excel;
[HttpPost]
public ActionResult ShowExcelFile(HttpPostedFileBase getFile)
{
if (getFile != null && getFile.ContentLength > 0)
{
// .xlsx
IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(getFile.InputStream);
// .xls
IExcelDataReader reader = ExcelReaderFactory.CreateBinaryReader(getFile.InputStream);
reader.IsFirstRowAsColumnNames = true; // if your first row contains column names
}
return PartialView("ShowExcelFile");
}
From that point it's hard to tell your exact needs without knowing the contents of your Excel file. You can convert the file to a System.Data.DataSet
which will contain every sheet and data of your Excel file.
DataSet dataSet = reader.AsDataSet();
Upvotes: 4
Reputation: 10694
Dont know what do you mean by
Make something with values of getFile
To get extension of file use
string fileExtension = Path.GetExtension(getFile.FileName);
//save this file using
string path = Path.Combine(Server.MapPath(Url.Content("~/Content")), "Name"+fileExtension);
file.SaveAs(path);
Upvotes: 0
Reputation: 33306
You could use a ViewModel to do this by adding it as a property:
View
@using (Html.BeginForm("ShowExcelFile", "ShowExcel", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.Files, new { type = "file", name = "Files" })<br />
<input type="submit" value="Upload file" />
}
Model
public class AModel
{
public AModel()
{
Files = new List<HttpPostedFileBase>();
}
public List<HttpPostedFileBase> Files { get; set; }
// Rest of model details
}
You can the retrieve the files by removing the un-needed parameter i.e.
Controller
[HttpPost]
public ActionResult ShowExcelFile(AModel model)
{
var file = model.Files[0];
...
}
Upvotes: 1