I want export data from DataTable into excel file using Response.Write.
However some of the data missing from the excel file. Can help me fix this.
I already try create html using StringBuilder and nothing wrong with the loop, can get all the data, only when export to excel it's missing. Please help me with this.
Response.Buffer = true;
Response.ClearContent();
Response.Write(HEADER);
Response.Write(STYLE);
Response.Write("</head><body><table border=\"0\" style=\"font-size:11pt\"><tr>");
Response.AddHeader("content-disposition", attachment);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Response.Write(strTitle);
Response.Write("</tr>");
Response.Write("<tr><td colspan=3>From Date: " + lblFromDate.Text + " To: " + lblToDate.Text + "</td></tr>");
Response.Write("<tr><td colspan=9>Protocol: " + lblProtocol.Text + "</td></tr>");
Response.Write("<tr><td colspan=9>Production Line: " + lblPL.Text + "</td></tr>");
Response.Write("<tr></tr></table>");
Response.Write("<table border=\"1\" style=\"font-size:11pt\">");
Response.Write("<tr>");
for (int i = 0; i < summaryreporttable.Columns.Count - 2; i++)
{
Response.Write(" <th>" + summaryreporttable.Columns[i].ToString() + "</th>");
}
Response.Write("</tr>");
for (int r = 0; r < summaryreporttable.Rows.Count; r++)
{
Response.Write("<tr>");
Response.Write("<td>"+r+"</td>");
for (int i = 0; i < summaryreporttable.Columns.Count - 2; i++)
{
if (summaryreporttable.Columns[i].ToString() == "Issue Date")
{
//Response.Write("<td class=\"x167\" valign=\"top\">" + summaryreporttable.Rows[r][i] + "</td>");
Response.Write(String.Format("<td class=\"x167\" valign=\"top\"> {0} </td>", summaryreporttable.Rows[r][i]));
}
else
{
//Response.Write("<td class=\"x169\" valign=\"top\">" + summaryreporttable.Rows[r][i] + "</td>");
Response.Write(String.Format("<td class=\"x169\" valign=\"top\"> {0} </td>", summaryreporttable.Rows[r][i]));
}
}
Response.Write("</tr>");
Response.Flush();
}
Response.Write("</table></body></html>");
}
catch (Exception ex)
{
}
finally
{
Response.End();
}
As you can see, the data between is missing.
I want to explain our way. This is usefull then yours.
1-we have a literal in the web page like this
<asp:Literal ID="lblData" runat="server" />
2-In the code we have some string variables. And we grow with html like drawing on a screen.
// our html datas
// you can use foreach for repating
sTEXT = #"<table class='table'><thead>";
sTEXT += #"<th>";
sTEXT += #"Caption A";
sTEXT += #"</th>";
sTEXT += #"</thead>";
sTEXT += #"<tr>";
sTEXT += #"<td>abcdef</td>";
sTEXT += #"<td>ghjklm</td>";
sTEXT += #"</tr>";
sTEXT += #"</table>";
// our screen literaldata sets
lblData.Text = sTEXT;
// excel output code
// carefull end of the "Responce.Write"" sentence
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1254");
Response.Charset = "windows-1254";
Response.AppendHeader("content-disposition", "attachment;filename=ExportedHtml.xls");
Response.Buffer = true;
this.EnableViewState = false;
Response.ContentType = "application/vnd.ms-excel";
Response.Write("<style> TABLE { border: 1px solid gray; } TD { border: 1px solid gray; } </style> " + lblData.Text);
Response.End();
Related
I read a few posts around here but couldn't find the answer so far.
I'm using the following code to export my GridView into Excel file:
protected void btnExportClick(object sender, EventArgs e)
{
StringBuilder builder = new StringBuilder();
string strFileName = "Report_" + DateTime.Now.ToShortDateString() + ".csv";
builder.Append("Firld1,Filed2,Field3,Field4,Field5" + Environment.NewLine);
foreach (GridViewRow row in gvMOSS2Merchants.Rows)
{
string f1= row.Cells[0].Text;
string f2= row.Cells[1].Text;
string f3= row.Cells[2].Text;
string f4= row.Cells[3].Text;
string f5= row.Cells[4].Text;
builder.Append(f1+ "," + f2+ "," + f3+ "," + f4+ "," + f5+ Environment.NewLine);
}
Response.Clear();
Response.ContentType = "text/cvs";
Response.AddHeader("Content-Disposition", "attachment;filename=" + strFileName);
Response.Write(builder.ToString());
Response.End();
}
When clicking on the button, the file is being created, but it has only headers and no data inside.
What can be wrong with that logic?
The following code works for me
this was called in button onclick event
OnClick="ExportExcel"
EXCEL EXPORT CODE
protected void ExportExcel(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=YourFileName" + DateTime.Now.ToString() + ".csv");
Response.Charset = "UTF8";
Response.ContentType = "application/text";
gridviewID.AllowPaging = false;
loadgrid();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < gridviewID.Columns.Count; k++)
{
//add separator
sb.Append(gridviewID.Columns[k].HeaderText.ToString() + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < gridviewID.Rows.Count; i++)
{
for (int k = 0; k < gridviewID.Columns.Count; k++)
{
//add separator
sb.Append(gridviewID.Rows[i].Cells[k].Text.Replace(",", " & ").Replace("\n", " ").Replace("\r", " ").ToString() + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
I am trying to generate excel with following code
public void GenerateExcel(string reportName, DataTable dt)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.ContentType = "application/ms-excel";
Response.Write(#"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
Response.AddHeader("Content-Disposition", "attachment;filename= " + reportName + ".xls");
Response.Charset = "utf-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
StringWriter ws = new StringWriter();
ws.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
// ws.Write("<BR><BR><BR>");
//sets the table border, cell spacing, border color, font of the text, background, foreground, font height
ws.Write("<Table border='1' bgColor='#ffffff' " +
"borderColor='#000000' cellSpacing='0' cellPadding='0' " +
"style='font-size:10.0pt; font-family:Calibri; background:white;'>");
string strBoldCell = "<TD bgColor='#c9c7c3' style=\"font-weight: bold\">{0}</TD>";
string strRedCell = "<TD style=\"background-color:#ff4d4d\">{0}</TD>";
string strCell = "<TD>{0}</TD>";
string strColSpan = "<TD colspan={0} style=\"font-weight: bold\">{1}</TD>";
int r;
int c;
if (dt.Rows.Count > 0)
{
try
{
ws.Write("<TR>");
for (c = 0; c < dt.Columns.Count; c++)
{
ws.Write(string.Format(strBoldCell, dt.Columns[c].ColumnName).Replace("_", ""));
}
ws.Write("</TR>");
ws.Write("\n");
for (r = 0; r < dt.Rows.Count; r++)
{
ws.Write("<TR>");
for (c = 0; c < dt.Columns.Count; c++)
{
if (string.IsNullOrEmpty(dt.Rows[r][dt.Columns[c].ColumnName].ToString()) == false)
{
if (dt.Rows[r]["Comment"].ToString() != null && dt.Rows[r]["Comment"].ToString() != "")
{
ws.Write(string.Format(strRedCell, dt.Rows[r][dt.Columns[c].ColumnName].ToString().Replace('_', ' ')));
}
else
{
ws.Write(string.Format(strCell, dt.Rows[r][dt.Columns[c].ColumnName].ToString().Replace('_', ' ')));
}
}
else
{
if (dt.Rows[r]["Comment"].ToString() != null && dt.Rows[r]["Comment"].ToString() != "")
{
ws.Write(string.Format(strRedCell, " "));
}
else
{
ws.Write(string.Format(strCell, " "));
}
}
}
ws.Write("</TR>");
ws.Write("\n");
}
}
catch (Exception ex)
{
throw ex;
}
}
else
{
ws.Write("<Tr>");
ws.Write(string.Format(strColSpan, 10, "No records found"));
ws.Write("</Tr>");
}
ws.Write("</Table>");
ws.Write("</Font>");
Response.Write(ws.ToString());
Response.Flush();
Response.End();
}
by calling above method in main method as follows
if (Cnt != 0)
{
TempData["Error"] = "There were issues with the Excel Import: Total Records: " + result.Rows.Count+" Error Row Count: "+Cnt;
}
else
{
TempData["Error"] = "No error found in given excel: Total Records: " + result.Rows.Count;
}
GenerateExcel("OutputFile" + DateTime.Now.ToString("MMddyyyyhhmmss"), result);
return View();
also trying to pass Tempdata to view but the problem is excel is generating successfully but tempdata does not showing anything in view.
if i comment the code of calling GenerateExcel method tempdata is perfectly showing on view..why this is happening?
Please Try moving calling function before setting tempdata like:
GenerateExcel("OutputFile" + DateTime.Now.ToString("MMddyyyyhhmmss"), result);
if (Cnt != 0)
{
TempData["Error"] = "There were issues with the Excel Import: Total Records: " + result.Rows.Count+" Error Row Count: "+Cnt;
}
else
{
TempData["Error"] = "No error found in given excel: Total Records: " + result.Rows.Count;
}
return View();
I have a GridView and a few columns are literal:
<asp:TemplateField HeaderText="Next Service Date">
<ItemTemplate>
<asp:Literal ID="litNextSvcDate" runat="server">/asp:Literal>
</ItemTemplate>
I want to convert this GridView to an Excel spreadsheet and all the boundfield columns display on the spreadsheet but not the literals. Here is the code to convert the Grid to Excel:
protected void ToExcel(GridView grid, string Name, string FileName)
{
if (!FileName.Contains(".xls"))
{
FileName = FileName + ".xls";
}
string style = "<style><!--table#page{mso-header-data:\"&C" + Name + " Date/: &D/ Page &P\"; mso-page-orientation:landscape; mso-page-scale:89;} br {mso-data-placement:same-cell;} --></style>";
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment; filename=" + FileName + "");
this.EnableViewState = false;
Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
Response.Write("<head>");
Response.Write(style);
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=windows-1252\">");
Response.Write("<!--[if gte mso 9]>");
Response.Write("<xml>");
Response.Write("<x:ExcelWorkbook>");
Response.Write("<x:ExcelWorksheets>");
Response.Write("<x:ExcelWorksheet>");
Response.Write("<x:Name>" + Name + " Table</x:Name>");
Response.Write("<x:WorksheetOptions>");
Response.Write("<x:Panes>");
Response.Write("</x:Panes>");
Response.Write("<x:Print>");
Response.Write("<x:ValidPrinterInfo/>");
Response.Write("<x:Scale>89</x:Scale>");
Response.Write("</x:Print>");
Response.Write("</x:WorksheetOptions>");
Response.Write("</x:ExcelWorksheet>");
Response.Write("</x:ExcelWorksheets>");
Response.Write("</x:ExcelWorkbook>");
Response.Write("</xml>");
Response.Write("<![endif]-->");
Response.Write("</head>");
Response.Write("<body>");
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
List<int> HiddenCols = new List<int>();
for(int i = 0; i < grid.Columns.Count; i++)
{
if (!grid.Columns[i].Visible)
{
HiddenCols.Add(i);
}
}
for (int i = 0; i < grid.HeaderRow.Cells.Count; i++)
{
if(HiddenCols.Contains(i))
grid.HeaderRow.Cells[i].Visible = false;
}
ClearControls(grid);
grid.RenderBeginTag(oHtmlTextWriter);
grid.HeaderRow.RenderControl(oHtmlTextWriter);
foreach (GridViewRow row in grid.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
if (HiddenCols.Contains(i))
row.Cells[i].Visible = false;
}
row.RenderControl(oHtmlTextWriter);
}
grid.FooterRow.RenderControl(oHtmlTextWriter);
grid.RenderEndTag(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.Write("</body>");
Response.Write("</html>");
Response.End();
}
I use this code to export datagridview to excel
HtmlForm form = new HtmlForm();
Response.Clear();
Response.Buffer = true;
string fileName = "TRAIL" + "[" + DatefromTxtBox.Text.Replace("/", "") + "_" + DatetoTxtBox.Text.Replace("/", "") + "]" + ".xls";
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
AuditTrailGV.AllowPaging = false;
AuditTrailGV.DataSource = (DataSet)ViewState["audit"];
AuditTrailGV.DataBind();
form.Controls.Add(AuditTrailGV);
this.Controls.Add(form);
form.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
the problem is this code also catches the formatting/borders of my gridview
here are the sample screen shots
This is my gridview in asp.net
and this is what appears in my excell
as you can see it transformed all of the lines like the gridview, i do not want it to happen, as much as possible if i can only retain the gridlines for the rows with data only, if its not possible, remove all the gridlines..
any help? i really do not like those gridlines in my excell
VB
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
'base.VerifyRenderingInServerForm(control);
'This remains empty
End Sub
Protected Sub btnExcel_Click(sender As Object, e As ImageClickEventArgs) Handles btnExcel.Click
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/vnd.ms-excel"
Dim stringWrite As New System.IO.StringWriter()
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
htmlWrite.Write("<html xmlns:o=""urn:schemas-microsoft-com:office:office"" ")
htmlWrite.Write("xmlns:x=""urn:schemas-microsoft-com:office:excel"" ")
htmlWrite.Write("xmlns=""http://www.w3.org/TR/REC-html40""> ")
htmlWrite.Write("<head> ")
htmlWrite.Write("<!--[if gte mso 9]><xml> ")
htmlWrite.Write("<x:ExcelWorkbook> ")
htmlWrite.Write("<x:ExcelWorksheets> ")
htmlWrite.Write("<x:ExcelWorksheet> ")
htmlWrite.Write("<x:Name>Sheet1</x:Name> ")
htmlWrite.Write("<x:WorksheetOptions> ")
htmlWrite.Write("<x:Selected/> ")
htmlWrite.Write("<x:ProtectContents>False</x:ProtectContents> ")
htmlWrite.Write("<x:ProtectObjects>False</x:ProtectObjects> ")
htmlWrite.Write("<x:ProtectScenarios>False</x:ProtectScenarios> ")
htmlWrite.Write("</x:WorksheetOptions> ")
htmlWrite.Write("</x:ExcelWorksheet> ")
htmlWrite.Write("</x:ExcelWorksheets> ")
htmlWrite.Write("</x:ExcelWorkbook> ")
htmlWrite.Write("</xml><![endif]--> ")
htmlWrite.Write("</head>")
htmlWrite.WriteLine("")
gridView.HeaderStyle.Reset()
gridView.FooterStyle.Reset()
gridView.AlternatingRowStyle.Reset()
gridView.RowStyle.Reset()
gridView.BackColor = Color.Transparent
gridView.GridLines = GridLines.None
gridView.RenderControl(htmlWrite)
Response.Write(stringWrite.ToString())
Response.[End]()
End Sub
C#
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
//This remains empty
}
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
htmlWrite.Write("<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" ");
htmlWrite.Write("xmlns:x=\"urn:schemas-microsoft-com:office:excel\" ");
htmlWrite.Write("xmlns=\"http://www.w3.org/TR/REC-html40\"> ");
htmlWrite.Write("<head> ");
htmlWrite.Write("<!--[if gte mso 9]><xml> ");
htmlWrite.Write("<x:ExcelWorkbook> ");
htmlWrite.Write("<x:ExcelWorksheets> ");
htmlWrite.Write("<x:ExcelWorksheet> ");
htmlWrite.Write("<x:Name>Sheet1</x:Name> ");
htmlWrite.Write("<x:WorksheetOptions> ");
htmlWrite.Write("<x:Selected/> ");
htmlWrite.Write("<x:ProtectContents>False</x:ProtectContents> ");
htmlWrite.Write("<x:ProtectObjects>False</x:ProtectObjects> ");
htmlWrite.Write("<x:ProtectScenarios>False</x:ProtectScenarios> ");
htmlWrite.Write("</x:WorksheetOptions> ");
htmlWrite.Write("</x:ExcelWorksheet> ");
htmlWrite.Write("</x:ExcelWorksheets> ");
htmlWrite.Write("</x:ExcelWorkbook> ");
htmlWrite.Write("</xml><![endif]--> ");
htmlWrite.Write("</head>");
htmlWrite.WriteLine("");
gridView.HeaderStyle.Reset();
gridView.FooterStyle.Reset();
gridView.AlternatingRowStyle.Reset();
gridView.RowStyle.Reset();
gridView.BackColor = Color.Transparent;
gridView.GridLines = GridLines.None;
gridView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
You can try below code and custom the color of the downloaded data. It will also not color the Column and rows other then the data.
protected void DownloadExcel_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Report.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
{
GridView1.HeaderRow.Cells[i].Style.Add("background-color", "#bfc2c7");
}
int j = 1;
foreach (GridViewRow gvrow in GridView1.Rows)
{
//gvrow.BackColor = color.White;
if (j <= GridView1.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
I try to generate word document using this code:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/doc";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;
filename=" + DateTime.Now + ".doc");
var strHTMLContent = new StringBuilder();
strHTMLContent.Append(
"<h1 title='Heading' align='Center'style='font-family: verdana; font
-size: 80 % ;color: black'><u>Document Heading</u> </h1> ");
strHTMLContent.Append("<br>");
strHTMLContent.Append("<table align='Center'>");
// Row with Column headers
strHTMLContent.Append("<tr>");
strHTMLContent.Append("<td style='width:100px; background:# 99CC00'>
<b>Column1 </b> </td>");
strHTMLContent.Append("<td style='width:100px;background:# 99CC00'>
<b>Column2 </b> </td>");
strHTMLContent.Append("<td style='width:100px; background:# 99CC00'>
<b>Column 3</b></td>");
strHTMLContent.Append(" </tr> ");
// First Row Data
strHTMLContent.Append("<tr>");
strHTMLContent.Append(
"<td style='width:100px'></td>");
strHTMLContent.Append(
"<td style='width:100px'>b</td>");
strHTMLContent.Append(
"<td style='width:100px'>c</td>");
strHTMLContent.Append("</tr>");
// Second Row Data
strHTMLContent.Append("<tr>");
strHTMLContent.Append(
"<td style='width:100px'>d</td>");
strHTMLContent.Append(
"<td style='width:100px'>e</td>");
strHTMLContent.Append(
"<td style='width:100px'>f</td>");
strHTMLContent.Append("</tr>");
strHTMLContent.Append("</table>");
strHTMLContent.Append("<br><br>");
strHTMLContent.Append(
"<p align='Center'> Note : This is a dynamically
generated word document </p> ");
HttpContext.Current.Response.Write(strHTMLContent);
// HttpContext.Current.Response.BinaryWrite(strHTMLContent);
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
It work fine but I want to make it landscape and in Print Layout cause it appears in Web Layout
Can anybody help me?
I found solution in this post. Solve like this:
Response.Write("<html>")
Response.Write("<head>")
Response.Write("<META HTTP-EQUIV=""Content-Type"" CONTENT=""text/html;
charset=UTF-8"">")
Response.Write("<meta name=ProgId content=Word.Document>")
Response.Write("<meta name=Generator content=""Microsoft Word 9"">")
Response.Write("<meta name=Originator content=""Microsoft Word 9"">")
Response.Write("<style>")
Response.Write("#page Section1 {size:595.45pt 841.7pt; margin:1.0in 1.25in 1.0in
1.25in;mso-header-margin:.5in;mso-footer-margin:.5in;mso-paper-source:0;}")
Response.Write("div.Section1 {page:Section1;}")
Response.Write("#page Section2 {size:841.7pt 595.45pt;mso-page-orientation:
landscape;margin:1.25in 1.0in 1.25in 1.0in;mso-header-margin:.5in;
mso-footer-margin:.5in;mso-paper-source:0;}")
Response.Write("div.Section2 {page:Section2;}")
Response.Write("</style>")
Response.Write("</head>")
Response.Write("<body>")
Response.Write("<div class=Section2>")
I solve this, it's work fine for me.
<style>
#page
{
mso-page-border-surround-header: no;
mso-page-border-surround-footer: no;
}
#page Section1
{
size:841.9pt 595.3pt;
mso-page-orientation:landscape;
margin: 0.7cm 0.7cm 0.7cm 0.7cm;
mso-header-margin: 42.55pt;
mso-footer-margin: 49.6pt;
mso-paper-source: 0;
layout-grid: 18.0pt;
}
div.Section1
{
page: Section1;
}
</style>
<div class="Section1"></div>
For Print layout use this code....
string strBody = string.Empty;
strBody = #"<html xmlns:o='urn:schemas-microsoft-com:office:office' " +
"xmlns:w='urn:schemas-microsoft-com:office:word'" +
"xmlns='http://www.w3.org/TR/REC-html40'>";
strBody = strBody + "<!--[if gte mso 9]>" +
"<xml>" +
"<w:WordDocument>" +
"<w:View>Print</w:View>" +
"<w:Zoom>100</w:Zoom>" +
"</w:WordDocument>" +
"</xml>" +
"<![endif]-->";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-word";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=ContentDocument.doc");
StringBuilder htmlCode = new StringBuilder();
htmlCode.Append("<html>");
htmlCode.Append("<head>"+strBody+" <style type=\"text/css\">body {font-family:arial;font-size:14.5;}</style></head>");
htmlCode.Append("<body>");
... populate htmlCode ...
htmlCode.Append("</body></html>");
HttpContext.Current.Response.Write(htmlCode.ToString());
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
I have not tried it myself but dont see the reason why it should not work
If you are already writing your html then show it as Word document, why not use css for page orientation like this :
#media screen and (orientation:landscape) {
body { opacity: 0; }
}