读取使用FileUpload Control上传的Excel文件,而不将其保存在服务器上

需要能够读取使用ASP.NET中的FileUploadControl上传的Excel文件。 该解决scheme将托pipe在服务器上。 我不想将Excel文件存储在服务器上。 我想直接将excel内容转换成数据集或数据表并利用。

下面是我已经find的两个解决scheme,但不会为我工作。

  1. LINQTOEXCEL – 当你在本地机器上有一个excel文件,并且你正在本地机器上运行你的代码时,这种方法是有效的。 在我的情况下,用户正尝试使用托pipe在服务器上的网页从本地机器上传Excel文件。

  2. ExcelDataReader – 我目前正在使用这个,但这是第三方工具。 我不能把这个移动到我们的客户。 另外,如果行/列交叉点正在携带一个公式,那么该行/列交集的数据不会被读入数据集。

我在google和StackOverflow上发现的大多数build议都是在Excel和.NET解决scheme都在同一台机器上时运行的。 但是在我的工作中,当解决scheme托pipe在服务器上时,我需要它来工作,并且用户正尝试使用本地机器上的托pipe网页来上传excel。 如果您有任何其他build议,可否请让我知道?

您可以使用HttpPostedFileInputStream属性将文件读入内存。

下面的示例演示了如何使用EPPlusHttpPostedFileIO.Stream创buildDataTable

 protected void UploadButton_Click(Object sender, EventArgs e) { if (FileUpload1.HasFile && Path.GetExtension(FileUpload1.FileName) == ".xlsx") { using (var excel = new ExcelPackage(FileUpload1.PostedFile.InputStream)) { var tbl = new DataTable(); var ws = excel.Workbook.Worksheets.First(); var hasHeader = true; // adjust accordingly // add DataColumns to DataTable foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column]) tbl.Columns.Add(hasHeader ? firstRowCell.Text : String.Format("Column {0}", firstRowCell.Start.Column)); // add DataRows to DataTable int startRow = hasHeader ? 2 : 1; for (int rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++) { var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column]; DataRow row = tbl.NewRow(); foreach (var cell in wsRow) row[cell.Start.Column - 1] = cell.Text; tbl.Rows.Add(row); } var msg = String.Format("DataTable successfully created from excel-file. Colum-count:{0} Row-count:{1}", tbl.Columns.Count, tbl.Rows.Count); UploadStatusLabel.Text = msg; } } else { UploadStatusLabel.Text = "You did not specify a file to upload."; } } 

这是VB.NET版本

 Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) If (FileUpload1.HasFile AndAlso IO.Path.GetExtension(FileUpload1.FileName) = ".xlsx") Then Using excel = New ExcelPackage(FileUpload1.PostedFile.InputStream) Dim tbl = New DataTable() Dim ws = excel.Workbook.Worksheets.First() Dim hasHeader = True ' change it if required ' ' create DataColumns ' For Each firstRowCell In ws.Cells(1, 1, 1, ws.Dimension.End.Column) tbl.Columns.Add(If(hasHeader, firstRowCell.Text, String.Format("Column {0}", firstRowCell.Start.Column))) Next ' add rows to DataTable ' Dim startRow = If(hasHeader, 2, 1) For rowNum = startRow To ws.Dimension.End.Row Dim wsRow = ws.Cells(rowNum, 1, rowNum, ws.Dimension.End.Column) Dim row = tbl.NewRow() For Each cell In wsRow row(cell.Start.Column - 1) = cell.Text Next tbl.Rows.Add(row) Next Dim msg = String.Format("DataTable successfully created from excel-file Colum-count:{0} Row-count:{1}", tbl.Columns.Count, tbl.Rows.Count) UploadStatusLabel.Text = msg End Using Else UploadStatusLabel.Text = "You did not specify an excel-file to upload." End If End Sub 

为了完整起见,这里是aspx:

 <div> <h4>Select a file to upload:</h4> <asp:FileUpload id="FileUpload1" runat="server"> </asp:FileUpload> <br /><br /> <asp:Button id="UploadButton" Text="Upload file" OnClick="UploadButton_Click" runat="server"> </asp:Button> <hr /> <asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </div> 
 //Best Way To read file direct from stream IExcelDataReader excelReader = null; //file.InputStream is the file stream stored in memeory by any ways like by upload file control or from database int excelFlag = 1; //this flag us used for execl file format .xls or .xlsx if (excelFlag == 1) { //1. Reading from a binary Excel file ('97-2003 format; *.xls) excelReader = ExcelReaderFactory.CreateBinaryReader(file.InputStream); } else if(excelFlag == 2) { //2. Reading from a OpenXml Excel file (2007 format; *.xlsx) excelReader = ExcelReaderFactory.CreateOpenXmlReader(file.InputStream); } if (excelReader != null) { //... //3. DataSet - The result of each spreadsheet will be created in the result.Tables ds = excelReader.AsDataSet(); //... ////4. DataSet - Create column names from first row //excelReader.IsFirstRowAsColumnNames = true; //DataSet result = excelReader.AsDataSet(); ////5. Data Reader methods //while (excelReader.Read()) //{ // //excelReader.GetInt32(0); //} //6. Free resources (IExcelDataReader is IDisposable) excelReader.Close(); } 

也许你可以看看Koogra这是一个开源Excel的读者(只读作家)我想你会从客户端得到一个stream。 然后,您可以像现在这样做所有事情从内存stream中读取并写入数据库。

我希望这有帮助。

这是如何在MVC中使用ClosedXML.Excel来完成的。 我知道这个答案为时已晚。 我只是想把这个答案给所有在Google上search这个网页后出现的问题。 在Visual Studio中,单击工具菜单并展开NuGet包pipe理器,然后运行包pipe理器控制台。键入以下命令:

 Install-Package ClosedXML 

该模型:

 namespace ExcelUploadFileDemo.Models { public class UploadFile { [Required] public HttpPostedFileBase ExcelFile { get; set; } } } 

控制器:

 namespace ExcelUploadFileDemo.Controllers { public class HomeController : Controller { public ActionResult Index() { UploadFile UploadFile = new UploadFile(); return View(UploadFile); } [HttpPost] public ActionResult Index(UploadFile UploadFile) { if (ModelState.IsValid) { if (UploadFile.ExcelFile.ContentLength > 0) { if (UploadFile.ExcelFile.FileName.EndsWith(".xlsx") || UploadFile.ExcelFile.FileName.EndsWith(".xls")) { XLWorkbook Workbook; Try//incase if the file is corrupt { Workbook = new XLWorkbook(UploadFile.ExcelFile.InputStream); } catch (Exception ex) { ModelState.AddModelError(String.Empty, $"Check your file. {ex.Message}"); return View(); } IXLWorksheet WorkSheet = null; Try//incase if the sheet you are looking for is not found { WorkSheet = Workbook.Worksheet("sheet1"); } catch { ModelState.AddModelError(String.Empty, "sheet1 not found!"); return View(); } WorkSheet.FirstRow().Delete();//if you want to remove ist row foreach (var row in WorkSheet.RowsUsed()) { //do something here row.Cell(1).Value.ToString();//Get ist cell. 1 represent column number } } else { ModelState.AddModelError(String.Empty, "Only .xlsx and .xls files are allowed"); return View(); } } else { ModelState.AddModelError(String.Empty, "Not a valid file"); return View(); } } return View(); } } } 

这个链接有很多例子,展示了处理各种excel的不同方式。

https://github.com/ClosedXML/ClosedXML/tree/9ac4d868a313f308b82e94617b9cc2d28baeb1c3/ClosedXML

风景

 @model ExcelUploadFileDemo.Models.UploadFile @{ ViewBag.Title = "Upload Excel File"; } <h2>Upload an Excel File</h2> @using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) { <div class="form-horizontal"> @Html.ValidationSummary("", new { @class = "text-danger" }); <div class="form-group"> @Html.LabelFor(model => model.ExcelFile, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.ExcelFile, new { type = "file", @class = "form-control" }) @Html.ValidationMessageFor(model => model.ExcelFile, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type = "submit" value="Submit" class="btn btn-default" /> </div> </div> </div> }