This example demonstrates how to use the ASPxUploadControl to let a user upload a Microsoft Excel file to the server and view the uploaded file's data in a Grid View.
Note: The example application uses the
DevExpress.Docs
assembly. The Document Server subscription license is required to use the demonstrated technique.
-
Add an ASPxGridView and ASPxUploadControl to a page.
-
Handle the upload control's ASPxUploadControl.FileUploadComplete event on the server and ASPxClientUploadControl.FileUploadComplete event on the client.
-
Use the
ASPxUploadControl.FileUploadComplete
handler to save the uploaded files to the"~/XlsTables/"
directory. Save the file path to the session.string FilePath { get { return Session["FilePath"] == null ? String.Empty : Session["FilePath"].ToString(); } set { Session["FilePath"] = value; } } protected void Upload_FileUploadComplete(object sender, DevExpress.Web.FileUploadCompleteEventArgs e) { FilePath = Page.MapPath("~/XlsTables/") + e.UploadedFile.FileName; e.UploadedFile.SaveAs(FilePath); }
-
Call the ASPxClientGridView.PerformCallback method from the
ASPxClientUploadControl.FileUploadComplete event
handler to refresh the Grid View after a file is uploaded.function OnFileUploadComplete(s, e) { Grid.PerformCallback(); }
-
Handle the ASPxGridView.Init event. Check the
Session["FileName"]
object's value in the event handler. If the value is notnull
, use the Spreadsheet Document API to export the saved Excel file to a DataTable object and bind the Grid View to this object.
protected void Grid_Init(object sender, EventArgs e) {
if (!String.IsNullOrEmpty(FilePath)) {
Grid.DataSource = GetTableFromExcel();
Grid.DataBind();
}
}
private DataTable GetTableFromExcel() {
Workbook book = new Workbook();
book.InvalidFormatException += book_InvalidFormatException;
book.LoadDocument(FilePath);
Worksheet sheet = book.Worksheets.ActiveWorksheet;
CellRange range = sheet.GetUsedRange();
DataTable table = sheet.CreateDataTable(range, false);
DataTableExporter exporter = sheet.CreateDataTableExporter(range, table, false);
exporter.CellValueConversionError += exporter_CellValueConversionError;
exporter.Export();
return table;
}
- Default.aspx (VB: Default.aspx)
- Default.aspx.cs (VB: Default.aspx.vb)
- Error.aspx (VB: Error.aspx)
- Error.aspx.cs (VB: Error.aspx.vb)
- Grid View for ASP.NET MVC - How to display data from an uploaded Excel file
- Grid View for Web Forms - How to upload files in Edit mode and see them on a click in Browse mode
(you will be redirected to DevExpress.com to submit your response)