Created
December 15, 2017 21:40
-
-
Save SmartyP/76ca05a5c26d8e1407588b1183f16fd9 to your computer and use it in GitHub Desktop.
ExcelDataReader test code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Create a stream for the file | |
Stream remoteStream = null; | |
Stream stream = null; | |
int bytesToRead = 10000; // This controls how many bytes to read at a time and send to the client | |
byte[] buffer = new Byte[bytesToRead]; // Buffer to read bytes in chunk size specified above | |
// The number of bytes read | |
try | |
{ | |
//Create a WebRequest to get the file | |
string url = "http://localhost:50915/Content/Import.xlsx"; | |
HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url); | |
//Create a response for this request | |
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse(); | |
if (fileReq.ContentLength > 0) | |
fileResp.ContentLength = fileReq.ContentLength; | |
//Get the Stream returned from the response | |
remoteStream = fileResp.GetResponseStream(); | |
stream = new MemoryStream(); | |
remoteStream.CopyTo(stream); | |
// Auto-detect format, supports: | |
// - Binary Excel files (2.0-2003 format; *.xls) | |
// - OpenXml Excel files (2007 format; *.xlsx) | |
DataSet dataset; | |
using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream)) | |
{ | |
// The result of each spreadsheet is in result.Tables | |
dataset = reader.AsDataSet(); | |
} | |
remoteStream.Close(); | |
stream.Close(); | |
ViewBag.Message += "Opened Excel file fine" + Environment.NewLine; | |
foreach (DataTable table in dataset.Tables) | |
{ | |
ViewBag.Message += $"Table found: {table.TableName}" + "<br>"; | |
ViewBag.Message += $"- columns: {table.Columns.Count}" + "<br>"; | |
ViewBag.Message += $"- rows: {table.Rows.Count}" + "<br>"; | |
foreach (DataRow row in table.Rows) | |
{ | |
string rowValues = string.Empty; | |
foreach (DataColumn col in table.Columns) | |
{ | |
object val = row[col]; | |
rowValues += val.ToString() + ", "; | |
} | |
rowValues += Environment.NewLine; | |
ViewBag.Message += $"- row: {rowValues}" + Environment.NewLine; | |
} | |
ViewBag.Message += Environment.NewLine; | |
ViewBag.Message += Environment.NewLine; | |
} | |
ViewBag.Message += dataset.Tables.Count + " tables found"; | |
} | |
catch (Exception ex) | |
{ | |
ViewBag.Message = "Exception reading file: " + ex.ToString(); | |
return View(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment