Export datatable value to word using c# - c#

I am new to asp.net and need to create a project. My requirement is I have a table where I will store data. This is my main table. Under each id I have a separate table:
Msg_id Src Dest
701 RADAR MSC
702 MSC RADAR
Msg_id Message_size Mgs_desc
701 256 PFM_Load
Like that it continues... I have 3 dropdown lists. The 1st one is msg_id, the 2nd is src and the 3rd is dest. I also have a submit button the user can select any one of the dropdown lists and the corresponding table should be displayed in MS-Word.

You will need to create report of this data in .NET
Use EnableRenderExtension( "HTML4.0", "MS Word" ); for this purpose.
Then will have to export that report into word file.
Follow link:
http://www.codeproject.com/Articles/35225/Advanced-Report-Viewer
Or
Step by Step Approach:
http://www.accelebrate.com/sql_training/ssrs_2008_tutorial.htm
Hope Its helpful.

u can use this:
THis code for export into csv formate which can open in both msword&msexcel:
private void OutPutFileToCsv(DataTable dt, string fileName, string seperator)
{
StringWriter stringWriter = new StringWriter();
Int32 iColCount = dt.Columns.Count;
for (Int16 i = 0; i < iColCount; i++)
{
stringWriter.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
if (seperator.Contains(";"))
stringWriter.Write(";");
else
stringWriter.Write(",");
}
}
stringWriter.Write(stringWriter.NewLine);
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
stringWriter.Write(dr[i].ToString().Trim());
}
if (i < iColCount - 1)
{
if (seperator.Contains(";"))
stringWriter.Write(";");
else
stringWriter.Write(",");
}
}
stringWriter.Write(stringWriter.NewLine);
}
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", fileName));
Response.ContentEncoding = Encoding.GetEncoding("iso-8859-1");
//Response.BinaryWrite(Encoding.Unicode.GetPreamble());
Response.Write(stringWriter.ToString());
Response.End();
}

just pass your datatable in function and get grid data in ms-word.
private void ExportToWord(DataTable dt)
{
if (dt.Rows.Count > 0)
{
string filename = "DownloadReport.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/msword";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
Hope it helps you.

Related

I want to export data to PDF/Excel

I want export data to Excel, for that I have use the code (linked below), code is working, data is being exported, but Excel is not downloading, please anyone can help me what is the problem?
Export data into Excel, Word and PDF with Formatting
This how I have use this code in my project
foreach (var enq_item in enquiries)
{
enquiry_list.Add(new enquiry_master
{
enquiry_source_id = enq_item.enquiry_source_id,
reference_no = enq_item.reference_no,
assigned_staff_no = enq_item.assigned_staff_no,
emp_id = enq_item.emp_id,
status_id = enq_item.status_id,
remarks = enq_item.remarks,
system_date_time = enq_item.system_date_time,
name = enq_item.name,
departing_from = enq_item.departing_from,
travelling_to = enq_item.travelling_to,
departing_date = enq_item.departing_date,
returning_date = enq_item.returning_date,
mobile_no = enq_item.mobile_no,
email = enq_item.email,
}
}
//Get the data from database into datatable
DataTable dt = ToDataTable(enquiry_list);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=DataTable.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
string filename = "DownloadTest.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//Apply text style to each Row
GridView1.Rows[i].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Write(hw.ToString());
Response.End();
Actually our requirement was need to export data to Excel or PDF then we realize best is PDF according to over requirements so I tried ItextSharp it's work out to me this my code
public string generatePDF()
{
string HTML = ""; ///Create a html as per our need
HTML += "<html>";
///Update the html here
HTML += "</html>";
string pdf_file_path = Request.PhysicalApplicationPath + "pdf\\quotations\\"; //getting physical application path for save the pdf
string final_name = "Here pdf name";
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdf_file_path + final_name, FileMode.Create));
wri.PageEvent = new ITextEvents();
doc.Open();
var content = wri.DirectContent;
content.MoveTo(28, doc.PageSize.Height - 150);
content.LineTo(28, doc.PageSize.Height - 200);
content.Stroke(); //generating line
content.MoveTo(573, doc.PageSize.Height - 150);
content.LineTo(573, doc.PageSize.Height - 200);
content.Stroke();
HTMLWorker htmlworker = new HTMLWorker(doc); //here we have to pass created instance of pdfWritter
htmlworker.SetStyleSheet(style);
htmlworker.Parse(new StringReader(HTML)); ///here pass the created HTML what we have need in the PDF
doc.NewPage();
doc.Close();
var json = JsonConvert.SerializeObject(final_name, Newtonsoft.Json.Formatting.Indented, common.JsonSerializeSettings());
return json; // retruning the file name
Response.Write(doc);
Response.End();
}
Above code is worked to me. Finally I'm returning the file name and showing the PDF in browser using the JavaScript

NewLine on CSV export of datatable

I have a datatable in a .Net web app that my customers have the option to export to CSV. A few customers have complained that the CSV is not able to re-import to our application. after further review, I noticed that on some large exports, the file has line breaks in it. is there a way i can prevent this?
here is my export method
DataTable dt = (DataTable)Session["Findings"];
string fileName = "test.csv";
string delimiter = ",";
//prepare the output stream
Response.Clear();
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition",
string.Format("attachment; filename={0}", fileName));
//write the csv column headers
for (int i = 0; i < dt.Columns.Count; i++)
{
Response.Write(dt.Columns[i].ColumnName);
Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine);
}
//write the data
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
Response.Write("\"" + row[i].ToString() + "\"");
Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine);
}
}
Response.End();
any help would be appreciated.
thanks

Execute codes after Response.End()

Im having trouble executing codes after Response.End().
Im using this to export a datatable/ASP Table to MS Excel(.xls).
The export finishes but my Gridview is not loading anymore. The command that I use to load the gridview is written after Response.End().
I tried using HttpContext.Current.ApplicationInstance.CompleteRequest(); but it did not help.
I tried also Response.Redirect("Charges_Trs.aspx", false); still did not work..
Any help please..Here is my code
lblNotif.Text = "Selected items have been posted. Exporting XLS ... (will be saved in your desktop)";
exportToExcel(dt); //calls the function to export the datatable to excel, i passed dt=datatable to this function
timerNotif.Enabled = true;
btnSearch_Click(null, null); //called the event of a button that loads the gridview
here is the function exporttoexcel()
public void exportToExcel(DataTable dt)
{
Table dTable = new Table();
TableRow dTableRow = new TableRow();
//Column Headings
for (int i = 0; i < dt.Columns.Count; i++)
{
TableCell tCell = new TableCell();
tCell.Text = dt.Columns[i].ToString();
dTableRow.Cells.Add(tCell);
}
dTable.Rows.Add(dTableRow);
//Rows
for (int i = 0; i < dt.Rows.Count; i++)
{
dTableRow = new TableRow();
for (int j = 0; j < dt.Columns.Count; j++)
{
TableCell tCell = new TableCell();
dTableRow.Cells.Add(tCell);
}
dTable.Rows.Add(dTableRow);
}
if (Response.IsClientConnected)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=PostedCharges" + DateTime.Now.ToString("MMddyyyy") + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
dTable.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
can u try adding the code in the btnSearch click event(hope it is to bind the grid with some data ) after calling export, instead of calling that click event.

How to export from DataTable to Excel file in text format (even if there are numbers)

I am using the following procedure to create an Excel spreadsheet from a DataTable:
protected void UploadDataTableToExcel(DataTable dtEmp, string filename)
{
string attachment = "attachment; filename=" + filename;
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = string.Empty;
foreach (DataColumn dtcol in dtEmp.Columns)
{
Response.Write(tab + dtcol.ColumnName);
tab = "\t";
}
Response.Write("\n");
foreach (DataRow dr in dtEmp.Rows)
{
tab = "";
for (int j = 0; j < dtEmp.Columns.Count; j++)
{
Response.Write(tab + Convert.ToString(dr[j]));
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
It works fine except when the cell only has numbers. For example:
This "6969062201223401504" becomes "6.96902E+18"
This "076854957" becomes "76854957"
I would like the Excel spreadsheet to preserve every column as text, instead of converting them into integers

Export Datatable to Excel without taking into consideration HTML tags

There are lots of methods in order to export datatable to Excel file.
But when a column includes HTML tags, the structure of Excel is corrupted, it seems like HTML document.
How can I prevent exporting datatable to excel without taking into consideration HTML tags?
Code I use is below:
public static void ExportToExcel(DataTable table, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn column in table.Columns)
{
context.Response.Write(column.ColumnName + ",");
}
context.Response.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
context.Response.Write(row[i].ToString().Replace(",", string.Empty) + ",");
}
context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".xls");
context.Response.End();
}
Use epplus
private void CreateExcel(DataTable dataTable)
{
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
ws.Cells["A1"].LoadFromDataTable(dataTable, true);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
}

Categories