I am writing an ASP.NET Application in c# and I'm trying to write a table to a word document.
I use currently the following code to write to a word doc:
string strContent = "This content goes to the word document";
string attach = "attachment; filename=wordtest.doc";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/msword";
HttpContext.Current.Response.AddHeader("content-disposition", attach);
HttpContext.Current.Response.Write(strContent);
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
Now, my question is if anyone knows how I can write a table to a word document?
And second question is if anyone knows how to write checkboxes to a word doc (like you copy it from a website and paste it in word)
Thanks in advance!
Killerwes
Word can recognise HTML. So you can simply write any HTML to MS WORD with Response.Write(); Method. Here is code sample.
string strBody = "<html>" +
"<body>" +
"<div>Your name is: <b>" + txtName.Text + "</b></div>" +
"<table width="100%" style="background-color:#cfcfcf;"><tr><td>1st Cell body data</td><td>2nd cell body data</td></tr></table>" +
"Ms Word document generated successfully." +
"</body>" +
"</html>";
string fileName = "MsWordSample.doc";
// You can add whatever you want to add as the HTML and it will be generated as Ms Word docs
Response.AppendHeader("Content-Type", "application/msword");
Response.AppendHeader ("Content-disposition", "attachment; filename="+ fileName);
Response.Write(strBody);
Related
I am using Nreco in mvc dotnet to export Html to Odt(Open office) file. But after getting exported image is not getting loaded in odt File. I have tried for Html to Pdf, which is working perfectly fine, but not in Html to Odt. Please look into the below code lines.
<div style="float:right; width:49%; text-align:right"><img
src="#(Url.Content("~/Content/img/logo.jpg"))" width="225"
height="44" alt="Logo" /></div>
Controller code:
HtmlToPdfConverter htmltoPdfObj = new HtmlToPdfConverter();
htmltoPdfObj.Orientation = PageOrientation.Default;
htmltoPdfObj.CustomWkHtmlArgs = "--margin-top 22 --header-spacing 10 --margin-bottom 20";
byte[] pdfContents = htmltoPdfObj.GeneratePdf(this.GetPDFScript() + htmlContractData + "</body></html>");
Response.Clear();
Response.Charset = "";
Response.ContentType = "application/vnd.oasis.opendocument.text";
string strFileName = "GenerateDocument" + ".odt";
Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
Response.Write(htmlContractData);
Response.End();
htmlContractData > plane cshtml text with above div Image.
Please help me out with this Issue troubling me since long
I am exporting data into Excel from a web page. This should be a no brainer, but there are <p> tags in the data. This causes Excel to create new rows when the data should all be in the same cell. After some research I found that mso-data-placement should do the trick, but it's not working. Excel opens, the data is displayed, but extra uncessary rows are created. Here is the code I use to export the data:
protected void doexcel()
{
string style = #"<style type='text/css'>P {mso-data-placement:same-cell; font-weight:bold;}</style>";
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
//set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
Random RandomClass = new Random();
int RandomNumber = RandomClass.Next();
String filename = "a" + RandomNumber + DateTime.Now + ".xls";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"" );
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
HttpContext.Current.Response.Write(style);
SqlDataSourceEmployeeAssets.ConnectionString = MyObjects.Application.CurrentContext.ConnectionString;
String sql = (string)Session["sql"];
SqlDataSourceEmployeeAssets.SelectCommand = sql;
// lCount.Text = "Query returned " + getCount(query) + " rows.";
DataGrid dge = new DataGrid();
dge.DataSource = SqlDataSourceEmployeeAssets;
dge.DataBind();
dge.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
This is an example of the raw data in the database that is giving me grief:
<P>4/13/2011 : Cheng "Jonathan" Vaing is with BSES Graffiti Unit.</P><P>4/13/2011 : Cheng "Jonathan" Vaing is with</P>
Suggestions?
I tried a couple of other things
I went straight to the data and added the mso-data-placement attribute to the paragraph tag inline. Still didn't work. The data looked like this
<P style="mso-data-placement:same-cell> my data </p>
I tried other mso-* attributes, that didn't work either. For example, I changed my stylesheet to look like this
<style type='text/css'>P {mso-highlight:yellow}</style>";
Why oh why doesn't Excel recognize my mso-* attributes?!?!
There is a solution but it is not clean.
After the dge.DataBind, place the following code. This will encode the text of each cell
foreach (DataGridItem dgi in dge.Items)
{
foreach (TableCell cell in dgi.Cells)
{
cell.Text = WebUtility.HtmlEncode(cell.Text);;
}
}
The Excel file, when opened, should show the raw data with the markup, all in one cell.
I found that this works because Excel actually encodes the text, as well. To see what Excel does in action, do the following:
Create a new workbook in Excel (I am using Office 2013).
In the first cell, paste the raw data (as you have it displayed). Do this by first pressing F2 (insert into cell), then paste the text.
Save the workbook as an HTML file (or web page).
Using windows explorer, go to the folder location of where you saved the file. There should be a hidden folder (i think it is hidden) with the same name as your file. For example, if your workbook is Book1.htm, there should be a folder labeled Book1_files.
In this folder, there should be an HTM file with the name sheet001.htm. Open this file in notepad (or any text editor...not excel or word)
Locate your raw data. You will see that the text is not showing the HTML markup, rather it is showing the encoded version.
Hope this helps.
Suppose I have a report Name as :
string reportName = "Facebook Network Performance Summary Report (By Region, By Content)";
and I would like to display that file name as excel
the below is my code to export the file
Response.AddHeader("Content-Disposition", "attachment; filename=" reportName + ".xls");
Response.AddHeader("Content-Length", l.ToString());
Response.ContentType = "application/vnd.ms-excel";
Response.BinaryWrite(f);
Unluckily, thewhen reading the first space of my reportName, it only shows Facebook and no else.
Is there any wexisting API for ASP.NET or other methods to handle the spaces of fileNAme ?
Try wrapping the filename in double quotes.
string filename = reportName + ".xls";
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
You need to wrap the filename in quotes:
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + reportName + "\".xls");
How about using verbatim string for this
string reportName = #"Facebook Network Performance Summary Report (By Region, By Content)";
try adding the # and/or double-double quotes before the double quotes to make c# read literals
Problem with spaces in a filepath - commandline execution in C#
Try this...
var fileName = HttpUtility.UrlEncode(document.FileName, Encoding.UTF8);
I have a grid in c# filled with data. One of the columns in that grid contains letters (followed by numbers) sorted alphabetically, like this:
A124
A256
A756
B463
B978
D322
etc.
I need to export this data in a word document (.doc or .docx format).
This is what i did to export a signle grid:
var dt = FuntionThatReturnsDatatables();
var gd = new GridView
{
DataSource = dt
};
gd.DataBind();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;
filename=" + "List" + DateTime.Now.ToString("dd.MM.yyyy") + ".doc");
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-word";
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
var oStringWriter = new StringWriter();
var oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
gd.RenderControl(oHtmlTextWriter);
HttpContext.Current.Response.Output.Write(oStringWriter.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
But now I have to follow this logic:
- For every letter from grid a new table with title should be created like this:
Table A:
A124
A256
A756
Each new table should start from a new page, like this:
Table A:
A124,
A256,
A756,
//new page
Table B:
B463,
B978,
//new page
Table D:
D322,
etc.
Pages in that word document need to be numbered.
Is there any way to write a code in c# to do this or is there some library/plugin that can accomplish this task ?
Some examples would be appreciated.
You should be able to use OpenXML SDK from Microsoft to achieve this.
Reference: http://msdn.microsoft.com/en-us/library/bb448854.aspx
Reference Sample:
http://blogs.msdn.com/b/acoat/archive/2010/06/19/document-creation-and-conversion-with-the-openxml-sdk-and-sharepoint-2010-word-automation-services.aspx
http://blogs.msdn.com/b/acoat/archive/2011/04/06/document-creation-and-conversion-with-the-openxml-sdk-and-sharepoint-2010-word-automation-services-part-2.aspx
What version of Word do you need to work with? If it's a version that can handle the .docx file format, i.e. 2007 and later, then you can generate those files directly. In fact, the easiest way to do that is create a .docx file in Word that you use as a kind of template, and then programmatically manipulate the xml in that file.
For more information, see
http://msdn.microsoft.com/en-us/magazine/cc163526.aspx
http://msdn.microsoft.com/en-us/library/system.io.packaging.aspx
I trying to export an HTML table named Table that is dynamically binded to ViewData.Model in C#. I have a method called export that is called based on another method's actions. so everything before that is set up.. I just don't know how to export the data to a CSV or Excel file.. So when the I step inside the Export method I don't know what next to do to export the table. Can someone help me
public void Export(List<data> List)
{
//the list is the rows that are checked and need to be exported
StringWriter sw = new StringWriter();
//I don't believe any of this syntax is right, but if they have Excel export to excel and if not export to csv "|" delimeted
for(int i=0; i<List.Count;i++)
{
sw.WriteLine(List[i].ID+ "|" + List[i].Date + "|" + List[i].Description);
}
Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.Write(sw);
Response.End();
}
I don't quite understand the whole "export an HTML table named Table that is dynamically binded to ViewData.Model" so I'll just ignore that and focus on your Export(List<data> list) method. Btw, you never really mentioned what was going wrong and where.
I see you had written "if they have Excel export to excel and if not export to csv" - I would personally just export it as a CSV file in both cases because excel can handle csv files no problem.
So with that in mind, here would be my export method based on your code.
public void Export(List<DataType> list)
{
StringWriter sw = new StringWriter();
//First line for column names
sw.WriteLine("\"ID\",\"Date\",\"Description\"");
foreach(DataType item in list)
{
sw.WriteLine(string.format("\"{0}\",\"{1}\",\"{2}\"",
item.ID,
item.Date,
item.Description));
}
Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
Response.ContentType = "text/csv";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.Write(sw);
Response.End();
}
This is an excellent example, but I think that need a globalization modification.
String ltListSeparator = CultureInfo.CurrentUICulture.TextInfo.ListSeparator;
sw.WriteLine(string.format("{0}" + ltListSeparator + "{1}" + ltListSeparator + "{2}", item.ID, item.Date, item.Description));
I think your controller action method will need to wrap the data items in an html table which you may want to do any way you like, So your html+ data will be stored in a string and then you could do something like below- (its not exacly built for MVC but its easy to modify for it).
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
Response.Write(yourDataAndHtmlAsString);
Response.End();
CSV is a simple format and can be built up easily as a string.
http://en.wikipedia.org/wiki/Comma-separated_values
You could create an excel spreadsheet of what you think the end product should look like, save as CSV, open it in notepad and try and replicate it using a string builder.