MVC and Export to Excel - c#

Description:
I tried the following code in MVC and received "OutputStream is not available when a custom TextWriter is used.". I followed the solution given in the URL http://blog.maartenballiauw.be/post/2008/05/ASPNET-MVC-custom-ActionResult.aspx. But my issue is not resolved.
Please help me to resolve this issue..
Code:
string json = e.ExtraParams["GridData"].ToString();
StoreSubmitDataEventArgs eSubmit = new StoreSubmitDataEventArgs(json, null);
XmlNode xml = eSubmit.Xml;
this.Response.Clear();
this.Response.ContentType = "application/vnd.ms-excel";
this.Response.AddHeader("Content-Disposition", "attachment;
filename=submittedData.xls");
XslCompiledTransform xtExcel = new XslCompiledTransform();
xtExcel.Load(Server.MapPath("Excel/XSLStyleSheet/Example2.xsl"));
xtExcel.Transform(xml, null, this.Response.OutputStream);
this.Response.End();
Error:
Server Error in '/' Application.
OutputStream is not available when a custom TextWriter is used.
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.Web.HttpException: OutputStream is not available when a custom TextWriter is used.
Source Error:
Line 85: XslCompiledTransform xtExcel = new XslCompiledTransform();
Line 86: xtExcel.Load(Server.MapPath("Excel/XSLStyleSheet/Example2.xsl"));
Line 87: xtExcel.Transform(xml, null, this.Response.OutputStream); <============== ERROR LINE
Line 88: this.Response.End();
Line 89: }

#Khalid's suggestion is good. If you really want to write to Excel XML I've had good results doing stuff with the ClosedXML library.

This might sound like a simple solution, but why not just ouput your data into a CSV format. Excel has no problems opening CSV spreadsheets.

Related

Closing Stream Error Message UTF 8 Encoding?

I've found zero info on this anywhere and hope someone can help me.
I'm trying to send a payment processing string to Authorize.Net using standard .NET streamwriter. The language I'm using is Visual Basic but even a C# example would be appreciated!
Here's my code:
strPost = "x_FirstName=John&x_LastName=Smith&x_Phone=1234567..ETC..."
Dim myWriter As StreamWriter = Nothing
Dim objRequest As HttpWebRequest = CType(WebRequest.Create("https://secure2.authorize.net/gateway/transact.dll"), HttpWebRequest)
objRequest.Method = "POST"
objRequest.ContentLength = strPost.Length
objRequest.ContentType = "application/x-www-form-urlencoded"
Try
myWriter = New IO.StreamWriter(objRequest.GetRequestStream())
myWriter.Write(strPost)
Catch e As Exception
Return e.Message
Finally
myWriter.Close()
End Try
If I run this code and type text into the text boxes on the page (which supply the values for the strPost variable), it works fine.
However, if I enter in an international character into a textbox (such as FirstName), or copy/paste someone's name from another web page, it fails with this message:
Server Error in '/' Application.
Cannot close stream until all bytes are written.
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.IO.IOException: Cannot close stream until all bytes are written.
For example if the letter รก is used instead of a, it fails with the error message above.
How do I revise this code to UTF-8 or strip out those characters, etc. and stop getting that message?
Thank you in advance!
-- Chris Lee
I was able to get the solution using a recommendation from jdweng. Here's the revised code:
Dim myWriter As StreamWriter = Nothing
Dim objRequest As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
objRequest.Method = "POST"
objRequest.ContentType = "application/x-www-form-urlencoded"
Try
myWriter = New IO.StreamWriter(objRequest.GetRequestStream())
myWriter.Write(strPost)
Catch e As Exception
Return e.Message
Finally
myWriter.Flush()
myWriter.Close()
End Try

Reading web page text content using Xml document

I am trying to read webpage text by using Xml Document:
XmlDocument document = new XmlDocument();
string site = "https://emailhunter.co/search/a-bs.com";
document.Load(site);
string allText = document.InnerText;
This is the exception i get:
An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
Additional information: The ';' character, hexadecimal value 0x3B, cannot be included in a name. Line 5, position 383.
I really don't understand what's wrong here. If you can give me some tips, I would really appreciate it.
You can use the Html Agility Pack like written in this post: What is the best way to parse html in C#?

Lumenworks CsvReader Exception

I need to parse a csv file and import it into a oracle database table. I use the Lumenworks Framework with this code:
using (CsvReader csv = new CsvReader(new StreamReader(sFile), true))
{
Console.WriteLine("test3");
}
But if I run the code, the following exception appears:
Application: Application.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
Stack:
at Application.Program.Main(System.String[])
But the weird thing is, if I only execute the new Streamreader(sFile) part and write this on the console, no exception appears. I already debugged the sFile and this is a valid path.
If you have a new StreamReader(sFIle); and the file does not exists it will throw an exception. The path could be a valid formatted path, but if the file is not there then the exception thrown, FileNotFoundException, would make perfect sense.
Check to make sure that the file exists at the specified path before trying to open the stream.
if (File.Exists(sFIle) {
using (CsvReader csv = new CsvReader(new StreamReader(sFile), true)) {
Console.WriteLine("test3");
}
}
What a mistake. After hours I realized that the Lumenworks.dll wasn't copied to the application.exe..
Another exception than System.IO.FileNotFoundException would be truly grateful.

Getting Error "Additional information: Reference to undeclared entity 'acirc'. Line 3325, position 145."

I am using the following code to read live xml url.
XmlDataDocument xmlDoc = new XmlDataDocument();
xmlDoc.Load("http://deluxecomm.com.au/feed.php");
I am getting the following error
Getting Error "Additional information: Reference to undeclared entity 'acirc'. Line 3325, position 145."
What I am doing wrong here!!!
You are trying to read HTML into an XML Data Document. HTML is not XML. They are both markup languages, but the two are not interchangeable.
You should look into using the HTML Agility Pack

HtmlAgilityPack in C# showing "A first chance exception of type 'System.UriFormatException' occurred in System.dll"

I have downloaded the following page using wget and saved it in f.html
http://www.ebay.com/sch/i.html?_nkw=gruen&_in_kw=1&_ex_kw=sara+quartz+embassy+bob+robert+elephants+adidas&_sacat=See-All-Categories&_okw=gruen&_oexkw=sara+quartz+embassy+bob+robert+elephants+adidas&_adv=1&_udlo=&_udhi=&_LH_Time=1&_ftrt=903&_ftrv=24&_sabdlo=&_sabdhi=&_samilow=&_samihi=&_sadis=200&_fpos=Zip+code&_fsct=&LH_SALE_CURRENCY=0&_sop=12&_dmd=1&_ipg=50
Now I want to load this page for parsing using HtmlAgilityPack in C#. Using this code snippet
var webGet = new HtmlWeb();
var document = webGet.Load("f.html");
Second line is throwing this error
A first chance exception of type 'System.UriFormatException' occurred in System.dll
What's the solution ??
I don't have the compiler at hand but I suppose that "f.html" is not a well formed Uri. It lacks the schema and the domain.
The correct uri should be like "http://the.domain.name/f.html".
Try the following:
var url = "http://www.ebay.com/sch/i.html?_nkw=gruen&_in_kw=1&_ex_kw=sara+quartz+embassy+bob+robert+elephants+adidas&_sacat=See-All-Categories&_okw=gruen&_oexkw=sara+quartz+embassy+bob+robert+elephants+adidas&_adv=1&_udlo=&_udhi=&_LH_Time=1&_ftrt=903&_ftrv=24&_sabdlo=&_sabdhi=&_samilow=&_samihi=&_sadis=200&_fpos=Zip+code&_fsct=&LH_SALE_CURRENCY=0&_sop=12&_dmd=1&_ipg=50";
var document = new HtmlDocument();
document.LoadHtml(new WebClient().DownloadString(url));
If you want to load it from a local file then try:
var file = "f.html";
var document = new HtmlDocument();
document.LoadHtml(File.ReadAllText(file));

Categories