2014-03-28 141 views
0

我的控制器:獲取從HttpPostedFileBase值MVC

[HttpPost] 
    public ActionResult ShowExcelFile(HttpPostedFileBase getFile) 
    { 
     //Make something with values of getFile 
     return PartialView("ShowExcelFile"); 
    } 

筆者認爲:

@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" /> 
} 

我怎樣才能讀取的GetFile值是多少?

+0

請看[Excel Data Reader](https://exceldatareader.codeplex.com/)。 – dom

回答

3

解析Excel文件的簡單方法是使用庫如Excel Data Reader(也可作爲Nuget package提供)。安裝完成後,閱讀你的Excel文件非常簡單。

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"); 
} 

從這一點來說,很難在不知道Excel文件內容的情況下告訴您確切的需求。您可以將文件轉換爲System.Data.DataSet,該文件將包含Excel文件的每個工作表和數據。

DataSet dataSet = reader.AsDataSet(); 
+0

從我的NuGet找不到Excel數據讀取器,但我試圖手動下載它。我在哪裏放置.dlls? – MrProgram

+0

@krillezzz [Nuget](https://www.nuget.org/packages/ExcelDataReader/)。或者您可以通過搜索「ExcelDataReader」在Visual Studio中查找它。 – dom

+0

謝謝。現在試試代碼 – MrProgram

1

你可以使用一個ViewModel爲此可以將其作爲一個屬性:

查看

@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" /> 
} 

型號

public class AModel 
{ 
    public AModel() 
    { 
     Files = new List<HttpPostedFileBase>(); 
    } 

    public List<HttpPostedFileBase> Files { get; set; } 
    // Rest of model details 
} 

您可以通過檢索文件刪除不需要的參數,即

控制器

[HttpPost] 
public ActionResult ShowExcelFile(AModel model) 
{ 
    var file = model.Files[0]; 
    ... 
} 
+0

現在就試試這個 – MrProgram

+0

這是行得通的,但我怎樣才能訪問文件的值?這是一個Excelfile,所以我該如何讀取文件? – MrProgram

+0

如果你需要訪問文檔本身,你應該得到ado.net適配器,並閱讀文件 – Jorge

0

不知道你是什麼意思由

讓與的GetFile

的價值觀的東西要獲得文件使用的擴展

string fileExtension = Path.GetExtension(getFile.FileName); 

//save this file using 



string path = Path.Combine(Server.MapPath(Url.Content("~/Content")), "Name"+fileExtension); 
file.SaveAs(path); 
相關問題