Skip to content

Instantly share code, notes, and snippets.

@SmartyP
Created December 15, 2017 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SmartyP/76ca05a5c26d8e1407588b1183f16fd9 to your computer and use it in GitHub Desktop.
Save SmartyP/76ca05a5c26d8e1407588b1183f16fd9 to your computer and use it in GitHub Desktop.
ExcelDataReader test code
//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