dg to excel and field format

T

Trapulo

Hello,
I wrote a library that wraps a datagrid or a gridview to output data in a
format that Excel can open. I stream output as
application/vnd.ms-excel. All works well, but the problem is that Excel
converts data to numbers, date, time and so on. I will only that it displays
all fields as simple plain text. Is there any way (css style attribute?) I
can use to force Excel to manage every cell as "text"?

My control simply wraps a datagrid and output data as an html table, with
CSS data inside.

Thanks
 
J

Jialiang Ge [MSFT]

Hello Trapulo,

From your post, my understanding on this issue is: you want to know how to
export Gridview to Excel and show all the integer fields as Text format in
the spreadsheet. If I'm off base, please feel free to let me know.

As you know, if we want to convert an integer Cell of Excel into Text, we
should add a quote before the string: "'". For instance,
Sheet1.Cells(2,2) = "'123123" 'Note the ' before 123123
When we view the Html format of this spreadsheet (Save the spreadsheet as
Html), the html tag for the cell (2, 2) is:
<td x:str="'123123">123123</td>
The namespace x is defined in the header of the html file:
xmlns:x="urn:schemas-microsoft-com:eek:ffice:excel"
Therefore, in order to export GridView and show all the interger fields as
Text format, we need to add the x:str attribute to <td> tag of table.
The blog page: http://jasonhaley.com/blog/archive/2004/03/20/9583.aspx
shows an example for your reference. Please have a try and let me know the
result. If you have any other concern or need anything else, please feel
free to let me know.

Sincerely,
Jialiang Ge ([email protected], remove 'online.')
Microsoft Online Community Support

==================================================
For MSDN subscribers whose posts are left unanswered, please check this
document: http://blogs.msdn.com/msdnts/pages/postingAlias.aspx

Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications. If you are using Outlook Express/Windows Mail, please make sure
you clear the check box "Tools/Options/Read: Get 300 headers at a time" to
see your reply promptly.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
 
T

Trapulo

That's very good, thanks!

I've inserted the xmlns into html head, but I've some problem inserting
x:str attribute in TD tag. I'll explain:
after I've created an htmlWriter and I wrote html, head, body, etc. tags, I
call
_gridview.RenderControl(htmlWriter)

to render the html table. This is very useful, because I can mantain ASP.NET
structure, and also use gridview events to manage output data. I don't know
I can insert the x:str attribute in code rendered by gridview or datagrid.
Can you help me?

thanks
 
J

Jialiang Ge [MSFT]

Hello Trapulo,

It seems that you are not rendering the table yourself as the blog
mentioned. A quick resolution I can think of is to replace all the "<td"
with "<td x:str=\"'\"" in the html string rendered from your gridview.
Please have a try and I will do further researches to see whether there is
better ways to do it.

Sincerely,
Jialiang Ge ([email protected], remove 'online.')
Microsoft Online Community Support

=================================================
When responding to posts, please "Reply to Group" via your newsreader
so that others may learn and benefit from your issue.
=================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
 
J

Jialiang Ge [MSFT]

Hello Trapulo,

I find a few more methods to add the x:str="'***" into the table cells.
Below is a summary of the solution.

Step1. Prepare the html header of export excel yourself. (NOTE: do not let
Excel itself automatically add the header, otherwise, the namespace in your
html would be replace)
String header = "<html xmlns:eek:=\"urn:schemas-microsoft-com:eek:ffice:eek:ffice\"
xmlns:x=\"urn:schemas-microsoft-com:eek:ffice:excel\"
xmlns=\"http://www.w3.org/TR/REC-html40\"> <head> <meta
http-equiv=Content-Type content=\"text/html; charset=windows-1252\"> <meta
name=ProgId content=Excel.Sheet> <meta name=Generator content=\"Microsoft
Excel 11\"> <style id=\"STI_5961_Styles\"><!--table
{mso-displayed-decimal-separator:\"\\.\";
mso-displayed-thousand-separator:\"\\,\";}.xlGeneral {padding-top:1px;
padding-right:1px; padding-left:1px; mso-ignore:padding; color:windowtext;
font-size:10.0pt; font-weight:400; font-style:normal; text-decoration:none;
font-family:Arial; mso-generic-font-family:auto; mso-font-charset:0;
mso-number-format:General; text-align:general; vertical-align:bottom;
mso-background-source:auto; mso-pattern:auto; white-space:nowrap;}
</style>--></head><body>"

Step2. Prepare the Response object
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=test.xls");
Response.ContentType = "application/vnd.xls";

Step3. Render the GridView
Now that you are using gridView.RenderControl(htmlTextWriter); to get it
html string, in order to add x:str="'***" into the table cells, here are
two approaches for your reference:

Approach 1. Add the attribute "x:str" to each cell of GridView before it's
rendered.
foreach (GridViewRow row in view.Rows) {
if (row.RowType == DataControlRowType.DataRow) {
foreach (TableCell cell in row.Cells) {
if (int.TryParse(cell.Text)) {
cell.Attributes.Add("x:str", "'" + cell.Text);
}}}}

Approach 2. Get the GridView's html first, then add the x:str into <td>
cells with Regex
Suppose the string htmlStr point to the render result of GridView. We could
use the regex:
<td (?<tdAttributes>[^>]*?)>(?<IntValue>\d*)</td>
to capture all the table cells with integer value. The group
(?<intValue\d*) refers to the int value, and the group
<tdAttributes>[^>]*?) is the original td attributes. We add a
MatchEvaluator function for the regex's Relace method:
public string replaceFunction(Match m)
{
String intValue = m.Groups["IntValue"].Value;
String tdAttributes = m.Groups["tdAttributes"].Value;
return "<td " + tdAttributes + " x:str=\"'" + intValue + "\">" + intValue +
"</td>";
}

Step4.
Response.Write(the html result string);
Response.End();

The methods above works well in my side. Please have a try and let me know
the result. If you have any other concern or need anything else, please
feel free to let me know.

Sincerely,
Jialiang Ge ([email protected], remove 'online.')
Microsoft Online Community Support

=================================================
When responding to posts, please "Reply to Group" via your newsreader
so that others may learn and benefit from your issue.
=================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
 
T

Trapulo

Thank you a lot!

I've implemented your approach 1 and it seems working.
I've tried approach 2 with datagrid (I support both datagrid and gridviews
because my library is born in net 1.0 era), but it doesn't work for me (it
seems all TD as unchanged). However this is not a problem: I upgraded the
page using a gridview, and removing the old datagrid, and it's all ok.

Thanks

p.s. if you are interested in, I've tried to implent the approach 2 as:
Dim prova As String = stringWriter.ToString

prova = System.Text.RegularExpressions.Regex.Replace(prova, "<td
(?<tdAttributes>[^>]*?)>(?<IntValue>\d*)</td>", New
Text.RegularExpressions.MatchEvaluator(AddressOf RegExIntCellEvaluator))

CurrentPage.Response.Write(prova)

and then

Private Function RegExIntCellEvaluator(ByVal m As
System.Text.RegularExpressions.Match) As String

Dim intValue As String = m.Groups("IntValue").Value

Dim tdAttributes As String = m.Groups("tdAttributes").Value

Dim value As Int32

If Int32.TryParse(intValue, value) Then

Return "<td " & tdAttributes & " x:str=""'" + intValue + """ > " & intValue
& "</td>"

Else

Return "<td> " & intValue & "</td>"

End If

End Function


Jialiang Ge said:
Hello Trapulo,

I find a few more methods to add the x:str="'***" into the table cells.
Below is a summary of the solution.

Step1. Prepare the html header of export excel yourself. (NOTE: do not let
Excel itself automatically add the header, otherwise, the namespace in
your
html would be replace)
String header = "<html xmlns:eek:=\"urn:schemas-microsoft-com:eek:ffice:eek:ffice\"
xmlns:x=\"urn:schemas-microsoft-com:eek:ffice:excel\"
xmlns=\"http://www.w3.org/TR/REC-html40\"> <head> <meta
http-equiv=Content-Type content=\"text/html; charset=windows-1252\">
<meta
name=ProgId content=Excel.Sheet> <meta name=Generator content=\"Microsoft
Excel 11\"> <style id=\"STI_5961_Styles\"><!--table
{mso-displayed-decimal-separator:\"\\.\";
mso-displayed-thousand-separator:\"\\,\";}.xlGeneral {padding-top:1px;
padding-right:1px; padding-left:1px; mso-ignore:padding; color:windowtext;
font-size:10.0pt; font-weight:400; font-style:normal;
text-decoration:none;
font-family:Arial; mso-generic-font-family:auto; mso-font-charset:0;
mso-number-format:General; text-align:general; vertical-align:bottom;
mso-background-source:auto; mso-pattern:auto; white-space:nowrap;}
</style>--></head><body>"

Step2. Prepare the Response object
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=test.xls");
Response.ContentType = "application/vnd.xls";

Step3. Render the GridView
Now that you are using gridView.RenderControl(htmlTextWriter); to get it
html string, in order to add x:str="'***" into the table cells, here are
two approaches for your reference:

Approach 1. Add the attribute "x:str" to each cell of GridView before it's
rendered.
foreach (GridViewRow row in view.Rows) {
if (row.RowType == DataControlRowType.DataRow) {
foreach (TableCell cell in row.Cells) {
if (int.TryParse(cell.Text)) {
cell.Attributes.Add("x:str", "'" + cell.Text);
}}}}

Approach 2. Get the GridView's html first, then add the x:str into <td>
cells with Regex
Suppose the string htmlStr point to the render result of GridView. We
could
use the regex:
<td (?<tdAttributes>[^>]*?)>(?<IntValue>\d*)</td>
to capture all the table cells with integer value. The group
(?<intValue\d*) refers to the int value, and the group
<tdAttributes>[^>]*?) is the original td attributes. We add a
MatchEvaluator function for the regex's Relace method:
public string replaceFunction(Match m)
{
String intValue = m.Groups["IntValue"].Value;
String tdAttributes = m.Groups["tdAttributes"].Value;
return "<td " + tdAttributes + " x:str=\"'" + intValue + "\">" + intValue
+
"</td>";
}

Step4.
Response.Write(the html result string);
Response.End();

The methods above works well in my side. Please have a try and let me know
the result. If you have any other concern or need anything else, please
feel free to let me know.

Sincerely,
Jialiang Ge ([email protected], remove 'online.')
Microsoft Online Community Support

=================================================
When responding to posts, please "Reply to Group" via your newsreader
so that others may learn and benefit from your issue.
=================================================
This posting is provided "AS IS" with no warranties, and confers no
rights.
 
J

Jialiang Ge [MSFT]

Hello Trapulo,

There is an error in my regex of approach 2. If there is no attributes
originally located in the <td>, for instance, <td>1</td>, the regex
<td (?<tdAttributes>[^>]*)>(?<IntValue>\d*)</td> is not able to match the
integers cells.
Please remove the space after '<td', change \d* to \d+ and try it again:
<td(?<tdAttributes>[^>]*)>(?<IntValue>\d+)</td>
Sorry for the inconveniences.

In the meantime, I notice that you use Int32.TryParse(intValue) to check if
the intValue is an integer. The regex (?<IntValue>\d+) ensures IntValue is
not an empty string and is composed of digials, therefore, we could
directly return "<td " & tdAttributes & " x:str=""'" + intValue + """ > " &
intValue & "</td>" in the end of RegExIntCellEvaluator function.

If you have any other concern or need anything else, please feel free to
let me know.

Sincerely,
Jialiang Ge ([email protected], remove 'online.')
Microsoft Online Community Support

=================================================
When responding to posts, please "Reply to Group" via your newsreader
so that others may learn and benefit from your issue.
=================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
 
T

Trapulo

Jialiang Ge said:
Hello Trapulo,

There is an error in my regex of approach 2. If there is no attributes
originally located in the <td>, for instance, <td>1</td>, the regex
<td (?<tdAttributes>[^>]*)>(?<IntValue>\d*)</td> is not able to match the
integers cells.
Please remove the space after '<td', change \d* to \d+ and try it again:
<td(?<tdAttributes>[^>]*)>(?<IntValue>\d+)</td>
Sorry for the inconveniences.

Thank you, this works
In the meantime, I notice that you use Int32.TryParse(intValue) to check
if
the intValue is an integer. The regex (?<IntValue>\d+) ensures IntValue is
not an empty string and is composed of digials, therefore, we could
directly return "<td " & tdAttributes & " x:str=""'" + intValue + """ > "
&
intValue & "</td>" in the end of RegExIntCellEvaluator function.

You are right. I forgot that the call is made only when value before passes
regex pattern test.

Thank you
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,077
Messages
2,570,567
Members
47,203
Latest member
EmmaSwank1

Latest Threads

Top