Am trying to read data from an Excel file into an ADO.NET Dataset using the code below. In a windows Forms application it work, but in an asp.net application it fails.
public static DataTable ArchiveData(string fileName)
{
FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);
//Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
//Free resources (IExcelDataReader is IDisposable)
excelReader.Close();
return result.Tables["Archive data"];
}
Stack Trace:
[HttpException (0x80004005): Maximum request length exceeded.]
System.Web.HttpRequest.GetEntireRawContent() +8793522
System.Web.HttpRequest.GetMultipartContent() +62
System.Web.HttpRequest.FillInFormCollection() +236
System.Web.HttpRequest.get_Form() +68
System.Web.HttpRequest.get_HasForm() +8745879
System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull) +97
System.Web.UI.Page.DeterminePostBackMode() +63
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +133
OR is there a better way of reading an Excel file from a client machine into an ADO.NET DataTable in ASP.NET
Add following tag in your web.config file and check if it works
<httpRuntime maxRequestLength="350000" enableVersionHeader="false" maxQueryStringLength="3584" executionTimeout="600"/>
Related
I am using OfficeOpenXml for reading the excel file in C#. But when I am trying to open and reading some sheet from it, it's throwing exception as below:
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
at MS.Internal.IO.Packaging.InternalRelationshipCollection.ProcessRelationshipAttributes(XmlCompatibilityReader reader)
at MS.Internal.IO.Packaging.InternalRelationshipCollection.ParseRelationshipPart(PackagePart part)
at MS.Internal.IO.Packaging.InternalRelationshipCollection..ctor(Package package, PackagePart part)
at System.IO.Packaging.PackagePart.EnsureRelationships()
at System.IO.Packaging.PackagePart.GetRelationshipHelper(String id)
at System.IO.Packaging.PackagePart.GetRelationship(String id)
at OfficeOpenXml.ExcelWorkbook.GetExternalReferences()
at OfficeOpenXml.ExcelPackage.get_Workbook()
at ServiceHandlerUNIC.UploadTuningFile() in d:\Srusti\Projects\WECSWebConfigurator\07_SourceCode\WECSWebConfigurator\App_Code\ServiceHandlerUNIC.cs:line 56392
How can I identify this thing? Because it's working with one excel file while another excel file is throwing an error. My code is :
ExcelPackage ep = new ExcelPackage(new FileInfo(fileFUllPath));
ExcelWorksheet ws = ep.Workbook.Worksheets["Configuration"];
I have a legacy code that imports Excel (*.xls) to our db, then move the file to specific directory after processing.
The code works fine except in one case, when the file is corrupted (even MS Excel cannot open it)! What happens in this case is that an System.AccessViolationException thrown at opening the connection!
Here is how the code looks like:
string connectionString = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1""", filePath);
OleDbConnection connection = new OleDbConnection(connectionString);
try
{
connection.ConnectionString = connectionString;
connection.Open(); //<<<--- exception throws here
//file processing
}
catch (Exception e)
{
//exception handling
}
finally
{
connection.Close();
connection.Dispose();
connection = null;
GC.Collect();
}
Here is the exception details...
System.AccessViolationException was caught
Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Source=System.Data
StackTrace:
at System.Data.Common.UnsafeNativeMethods.IDBInitializeInitialize.Invoke(IntPtr pThis)
at System.Data.OleDb.DataSourceWrapper.InitializeAndCreateSession(OleDbConnectionString constr, SessionWrapper& sessionWrapper)
at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.OleDb.OleDbConnection.Open()
As you can see, I am catching this exception and process it, then when the code try to move the file to another directory, I got the following exception:
System.IO.IOException occurred
Message=The process cannot access the file because it is being used by another process.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.__Error.WinIOError()
at System.IO.File.Move(String sourceFileName, String destFileName)
I tried to use another library, like LinqToExcel, but found it internally uses the same implementation like mine, then it is has the same problem!
I tried also to run garbage collector after the connection is closed (as you see in the above code) but faced the same problem!
Any Idea?
I tried to play around the main solution in the question with no results :(
I even checked the .NET Framework code and can see file handles somewhere in the code, but unfortunately failed to debug the code :(
I tried to decompile the .NET Framework code but failed too :(
Finally. it ends that I should use another solution, and since depending on the existence of MS Office in production machine is not an option, I went to ExcelDataReader, the open source library that reads *.xls files as binary streams, and here is how the final code looks like:
using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream, true))
{
excelReader.IsFirstRowAsColumnNames = true;
var excelFileDataSet = excelReader.AsDataSet();
var sheetDataTable = excelFileDataSet.Tables["sheetName"];
//other file processing code...
}
}
And this solution works for me!
I have the same problem right now, my only solution its read the excel file using Microsoft.Office.Interop.Excel and set the MsoFileValidationMode = msoFileValidationSkip;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook;
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
**xlApp.FileValidation = MsoFileValidationMode.msoFileValidationSkip;**
xlWorkbook = xlApp.Workbooks.Open(#"C:\my file.xls");
Excel.Sheets xlWorksheet = xlWorkbook.Worksheets;
Excel.Worksheet worksheet = (Excel.Worksheet)xlWorksheet.get_Item(3);
for (int i = 1; i <= 10; i++)
{
Excel.Range range = worksheet.get_Range("A" + i.ToString(), "B" + i.ToString()); ; //UsedRange;
System.Array myvalues = (System.Array)range.Cells.Value2;
string[] strArray = ConvertToStringArray(myvalues);
foreach (string item in strArray)
{
MessageBox.Show(item);
}
}
... works well
So this is what I have so far
in my view
#foreach (var file in item.AssociatedFileList)
{
#Html.ActionLink(file.FileName, "GetFile", "Landing", new { path = file.FilePath }, new { target = "_blank" }) <br /><br />
}
and my controller
public ActionResult GetFile(string path)
{
var extension = Path.GetExtension(path);
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
if (extension == ".pdf")
return File(fs, "application/pdf", Path.GetFileNameWithoutExtension(path));
if (extension == ".xlsx" || extension == ".xls")
return File(fs, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", Path.GetFileNameWithoutExtension(path));
if (extension == ".zip")
return File(fs, "application/zip", Path.GetFileNameWithoutExtension(path));
return this.Content("<html><center><span style='font-size: large; font-weight: bold; font-family: 'Century Gothic', 'PT Sans', 'Verdana', 'Arial', 'Helvetica', 'sans-serif'; color: #FF0000;'>There is no file to view<span></center></html>");
}
The logic behind displaying the file is ruled by case and sub case
1 case - multiple sub case.
Each subcase is represented by different file types(pdf, excel or zip)
the directory name is case name and file is the directory is subcase with appropriate extension.
to sum it up
C drive has a folder name my application -> it has a account number folders -> each account has miltiple case folder click on one case say CASE_1 folder -> its has SUBCASE_1.pdf , SUBCASE_2.xlsx , SUBCASE_3.zip etc files
Now each file is displayed on screen independently note: the files have to be displayed independently not zipped at directory(case) level. when user clicks the action link they can read or download.
#Html.ActionLink(file.FileName, "GetFile", "Landing", new { path = file.FilePath }, new { target = "_blank" }) <br /><br />
These zip files can be huge
the problem i am facing is when only one user is trying to access the file everything works fine but if more than one user tries to access the file I get
Server Error in '/' Application.
Exception of type 'System.OutOfMemoryException' was thrown.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.]
System.IO.MemoryStream.set_Capacity(Int32 value) +93
System.IO.MemoryStream.EnsureCapacity(Int32 value) +64
System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) +330
Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.ArteryFilter.Write(Byte[] buffer, Int32 offset, Int32 count) +106
System.Web.HttpWriter.FilterIntegrated(Boolean finalFiltering, IIS7WorkerRequest wr) +9509748
System.Web.HttpResponse.FilterOutput() +104
System.Web.CallFilterExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +49
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
later I checked the file size of filestream oibject it is 108560843
I am putting everything I can think of in the question. this is my first time working with files and I don't want to miss any detail.
I want to export the report viewer to excel file after clicking a button and hide the existing export toolstrip button that available for report viewer.
Below is my code for ExportFile function:
private void ExportFile()
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "*PDF files (*.pdf)|*.pdf|Excel files (*.xls)|*.xls|Doc files (*.doc)|*.doc";
// Variables
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string extension;
string path = " ";
DialogResult dr = saveFileDialog1.ShowDialog();
path = saveFileDialog1.FileName;
byte[] bytes = reportViewerForm.reportViewer1.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamids, out warnings);
FileStream fs = new FileStream(path + ".xls", FileMode.Create);
fs.Write(bytes, 0, bytes.Length);
fs.Close();}
Code for button_click event:
private void btnExport_Click(object sender, EventArgs e)
{
this.GetData();
this.ExportFile();
}
However, I get a exception error when trying to export it.
Here is my inner exception:
InnerException: Microsoft.ReportingServices.ReportProcessing.ReportProcessingException
Message=One or more parameters required to run the report have not been specified.
Source=Microsoft.ReportViewer.Common
ExceptionLevelHelpLink=http://go.microsoft.com/fwlink/?LinkId=20476&EvtSrc=Microsoft.ReportingServices.Diagnostics.Utilities.ErrorStrings&EvtID=rsParametersNotSpecified&ProdName=Microsoft%20SQL%20Server%20Reporting%20Services&ProdVer=1.0
SkipTopLevelMessage=false
StackTrace:
at Microsoft.ReportingServices.ReportProcessing.ReportProcessing.RenderReport(IRenderingExtension newRenderer, DateTime executionTimeStamp, ProcessingContext pc, RenderingContext rc, IChunkFactory cacheDataChunkFactory, IChunkFactory yukonCompiledDefinition, Boolean& dataCached)
at Microsoft.Reporting.LocalService.CreateSnapshotAndRender(CatalogItemContextBase itemContext, ReportProcessing repProc, IRenderingExtension renderer, ProcessingContext pc, RenderingContext rc, SubreportCallbackHandler subreportHandler, ParameterInfoCollection parameters, DatasourceCredentialsCollection credentials)
at Microsoft.Reporting.LocalService.Render(CatalogItemContextBase itemContext, Boolean allowInternalRenderers, ParameterInfoCollection reportParameters, IEnumerable dataSources, DatasourceCredentialsCollection credentials, CreateAndRegisterStream createStreamCallback, ReportRuntimeSetup runtimeSetup)
at Microsoft.Reporting.WinForms.LocalReport.InternalRender(String format, Boolean allowInternalRenderers, String deviceInfo, PageCountMode pageCountMode, CreateAndRegisterStream createStreamCallback, Warning[]& warnings)
InnerException:
What parameter did I missing? Any help will be appreciated. Thank you.
Does the report you are trying to export require Report Parameters?
(Quick Info on Parameters: how to add parameters in report viewer?)
I ask because that's usually the Exception I get when I forget to pass my report Parameters.
I am getting the following error on click of a button ,
On click of a button i am calling the following method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
/// <summary>
/// Summary description for pdfgeneration
/// </summary>
public class pdfgeneration
{
public pdfgeneration()
{
//
// TODO: Add constructor logic here
//
}
public void pdfgenerator(String name1, AjaxControlToolkit.HTMLEditor.Editor Editor1)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
// Create PDF document
Document pdfDocument = new Document(PageSize.A4, 70, 55, 40, 25);
PdfWriter wri = PdfWriter.GetInstance(pdfDocument, new FileStream("e://" +name1 + ".pdf", FileMode.Create));
PdfWriter.GetInstance(pdfDocument, HttpContext.Current.Response.OutputStream);
pdfDocument.Open();
string htmlText = Editor1.Content;
System.Collections.Generic.List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(htmlText), null);
for (int k = 0; k < htmlarraylist.Count; k++)
{
pdfDocument.Add((IElement)htmlarraylist[k]);
}
pdfDocument.Close();
HttpContext.Current.Response.End();
}
}
the stack trace is:
[FormatException: Input string was not in a correct format.]
System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) +7471335
System.Number.ParseSingle(String value, NumberStyles options, NumberFormatInfo numfmt) +115
System.Single.Parse(String s, NumberStyles style, NumberFormatInfo info) +192
iTextSharp.text.html.simpleparser.CellWrapper..ctor(String tag, ChainedProperties chain) +148
iTextSharp.text.html.simpleparser.HTMLTagProcessor_TD.StartElement(HTMLWorker worker, String tag, IDictionary`2 attrs) +84
iTextSharp.text.html.simpleparser.HTMLWorker.StartElement(String tag, Dictionary`2 attrs) +79
iTextSharp.text.xml.simpleparser.SimpleXMLParser.ProcessTag(Boolean start) +30
iTextSharp.text.xml.simpleparser.SimpleXMLParser.Go(TextReader reader) +1008
iTextSharp.text.xml.simpleparser.SimpleXMLParser.Parse(ISimpleXMLDocHandler doc, ISimpleXMLDocHandlerComment comment, TextReader r, Boolean html) +48
iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(TextReader reader, StyleSheet style, IDictionary`2 tags, Dictionary`2 providers) +94
iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(TextReader reader, StyleSheet style) +9
pdfgeneration.pdfgenerator(String name1, Editor Editor1) in C:\inetpub\wwwroot\dcis\App_Code\pdfgeneration.cs:37
EntryForm.Button4_Click(Object sender, EventArgs e) in C:\inetpub\wwwroot\dcis\EntryForm.aspx.cs:224
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
How can I resolve this error?
# geek for error in the code he has posted
I have facing same error, "Input string was not in a correct format.", i check my html string and found that, if i write table width outside of style tag, i get this error,
For eg, :- Give error at htmlWorker.Parse() method.
when i put width tag in style tag, i resolve this error,
For eg,
I hope, this will help you little bit.
For eg, <table width="610px"> </table> :- Give error at htmlWorker.Parse() method.
when i put width tag in style tag, i resolve this error,
For eg, <table style="width:610px"> </table>
I hope, this will help you little bit.
You could start by narrowing it down within pdfgenerator... Enabling build symbols for that dll would be a start, but even some simple tracing so that you can tell where it got to when it exploded would help.
Ultimately PdfWriter isn't core .NET, so you will have to help us narrow it down.
Or even simpler: hit "Start Debugging", and put a break-point on that method; now step through and see a: where it explodes, and b: what the key values are at that point.
This looks like you've got a non-numeric style value where iTextSharp is expecting a number. "font-size:normal" or something like that.
CellWrapper(String, ChainedProperties) is looking at the HtmlTags.WIDTH. Here's the source from iTextSharp 5.0.6:
public CellWrapper(String tag, ChainedProperties chain) {
this.cell = CreatePdfPCell(tag, chain);
String value = chain[HtmlTags.WIDTH];
if (value != null) {
value = value.Trim();
if (value.EndsWith("%")) {
percentage = true;
value = value.Substring(0, value.Length - 1);
}
width = float.Parse(value, CultureInfo.InvariantCulture);
}
}
It looks an awful lot like the problem is in the float.Parse() call. It looks like this code can't handle anything but '%' or a bald number. If your width is defined in 'cm', 'px', or whatever, that may well be the problem.
Use the Source!
PS: What version are you using? IIRC, iText has been shipping with debug info for quite some time. If all else fails, just build a debug version yourself.
I was having the same problem you had and I found another solution.
That error occurs when it tries to parse a size with the "px" part. To solve it, just replace the HTML string "px" occurences for "". It still knows that it is pixels.
Hope it works on your case!
try this
public void CreatePDFDocument(string strHtml)
{
string strFileName = HttpContext.Current.Server.MapPath("test.pdf");
// step 1: creation of a document-object
Document document = new Document();
// step 2:
// we create a writer that listens to the document
PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
StringReader se = new StringReader(strHtml);
HTMLWorker obj = new HTMLWorker(document);
document.Open();
obj.Parse(se);
document.Close();
ShowPdf(strFileName);
}
public void ShowPdf(string strFileName)
{
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
Response.ContentType = "application/pdf";
Response.WriteFile(strFileName);
Response.Flush();
Response.Clear();
}