Export data into Excel, Word and PDF with Formatting - asp.net

I want to export data of DataTable or DataSet with formating like Color of Header-Footer, Font Size, Row Color in Word, Excel and PDF format. Is it possible?
If yes then how? Please healp me.
My code is as below.
public void ExportToExcel(DataTable dt)
{
con.Open();
string sql = "select *from test";
cmd = new SqlCommand(sql, con);
dt = new DataTable();
da = new SqlDataAdapter(cmd);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
cmd.Dispose();
string filename = "DownloadTest.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();
DataSet ds = new DataSet();
ds = dt.Clone;
dgGrid.RenderControl(hw);
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
con.Close();
}

for pdf :-
I think you should use 'itextSharp'. You can go through this link http://www.codeproject.com/Articles/81118/ITextSharp-Helper-Class
You can download it (.dll) from here
http://sourceforge.net/projects/itextsharp/
For excel and word you can use gridview to export it to excel and word with color and fonts.
for excel you can go through this link

Related

ASP.Net Open office XML Set the values of a cell

I am using ASP.Net and Open office XML and I have been able to set the headers of the excel file.
However, I want to set the value to cells from say D2 to D1000 in a drop down fashion i.e. that the user can only select from a predefined list of values as in a drop down list.
How do I accomplish this?
The code for creating the excel is
List<ExcelExport> mpList = new List<ExcelExport>();
DataTable dt = ListToDataTable(mpList);
string attachment = string.Format("attachment;filename={0}-{1}.xlsx", ddlHealthFacility.SelectedItem.Text + " Excel export ", " ");
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Monthly Plan");
ws.Cells["A1"].LoadFromDataTable(dt, true);
Byte[] fileBytes = pck.GetAsByteArray();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", attachment);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
Response.BinaryWrite(fileBytes);
Response.End();
}

What is the best way to create .xls from datatable in asp .Net c#?

i have a datatable and i want to export excel from that,
my datatable contains unicode characters (persian characters) and i want to convert it to .xls files correctly.
i was wonder is it possible to do that with Stimulsoft?
This is a common method I use
public void ExportDetails(DataTable tempDataTable, string FileName)
{
try
{
System.IO.StringWriter objStringWriter1 = new System.IO.StringWriter();
System.Web.UI.WebControls.GridView gridView1 = new System.Web.UI.WebControls.GridView();
System.Web.UI.HtmlTextWriter objHtmlTextWriter1 = new System.Web.UI.HtmlTextWriter(objStringWriter1);
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
gridView1.DataSource = tempDataTable;
gridView1.DataBind();
gridView1.HeaderStyle.Font.Bold = true;
gridView1.HeaderStyle.BackColor = System.Drawing.Color.Gray;
gridView1.RenderControl(objHtmlTextWriter1);
gridView1.Dispose();
HttpContext.Current.Response.Write(objStringWriter1.ToString());
HttpContext.Current.Response.End();
}
catch (Exception ex)
{
}
}

Add Title before Export Excel

Am using the Following Function for Export the Excel File.It Was working Fine.I retrieve the Records from SQL DataBase to data table and I Export the Excel Sheet.
public ActionResult ExporttoExcel()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection("Connection string here");
con.Open();
SqlCommand cmd = new SqlCommand("select * from Exportxcel", con);
dt.Load(cmd.ExecuteReader());
int total = 0;
foreach (DataRow row in dt.Rows)
{
int salaryvalue = Convert.ToInt32(row["Salary"]);
total = salaryvalue + total;
}
dt.Rows.Add(new object[] { "", "Total", total });
if (dt.Rows.Count > 0)
{
string filename = "ExcelExport.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();
dgGrid.RenderControl(hw);
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.Write(tw.ToString());
Response.End();
}
return View(dt);
}
My question is I need to add Two title before the Value Bind?How to do this?I need to add Title ,author like the following Screen Shot.How to do this?
You could try adding this just after declaring System.Web.UI.HtmlTextWriter hw
hw.Write("<table><tr><td colspan='3'>Title</td></tr>")
hw.Write("<table><tr><td colspan='3'>Author</td></tr>")

Passing a grid to a function used to export to excel

I have a method that is used to export the data to excel.Till now I have been passing table to the method.But now I wish to pass the grid data so that I do not have to call the procedures for different instances for getting different filtered data sets.
is there a way to do so?
public void ExportToExcel(DataSet ds)
{
if (ds.Tables[0].Rows.Count > 0)
{
string filename = ds.Tables[1].Rows[0]["filename"].ToString() + ".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 = ds.Tables[0];
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.Clear();
Response.ClearHeaders();
Response.Charset = "";
Response.AddHeader("content-disposition", String.Concat("attachment;filename=", filename));
Response.AddHeader("Cache-Control", "max-age=0");
Response.ContentType = "application/vnd.xls";
// this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
This is the method that I am using to export to excel.

Exporting data to excel in vb.net

I am unable to export my data into excel.
I have tried the suggestions on S/O, but have not had any luck.
Dim sqlString As String = "spExportRateProfile" & Session("OfficeNumber") & "," & Session("SalesRepID")
Dim conn As SqlConnection = New SqlConnection(Utils.GetConfigKey("ConnectionStringVimas"))
conn.Open()
Dim dt As DataTable = New DataTable()
Dim da As SqlDataAdapter = New SqlDataAdapter(sqlString, conn)
da.Fill(dt)
Response.AddHeader("content-disposition", "attachment;filename=ReportExport.xlsx")
Response.ContentType = "application/vnd.ms-excel"
What do I need do after this to export my data to excel?
You could use a ExcelLibrary like EPPlus(GPL) which i can warmly recommend.
Then it is as easy as this to create Excel-Files from a DataTable and write it to the Response:
Dim pck = New ExcelPackage()
Dim ws = pck.Workbook.Worksheets.Add("Worksheet-Name")
ws.Cells("A1").LoadFromDataTable(dt, True, OfficeOpenXml.Table.TableStyles.Medium1)
Response.Clear()
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment; filename=ExcelFileName.xlsx")
Response.BinaryWrite(pck.GetAsByteArray())
Here is another example: http://epplus.codeplex.com/wikipage?title=WebapplicationExample
once you have your datatable dt here you should do this (C# - just copied from the Internet)
...
da.Fill(dt);
Response.ContentType = "Application/x-msexcel";
Response.AddHeader("content-disposition", "attachment; filename=\"test.csv\"");
Response.Write((new ExportXMLCSV()).ToCSV(dt));
Response.End();
and here the method ToCSV of the class ExportXMLCSV (C# - just copied from the Internet)
public string ToCSV(DataTable dataTable)
{
//create the stringbuilder that would hold our data
StringBuilder sb = new StringBuilder();
//check if there are columns in our datatable
if (dataTable.Columns.Count != 0)
{
//loop thru each of the columns so that we could build the headers
//for each field in our datatable
foreach (DataColumn column in dataTable.Columns)
{
//append the column name followed by our separator
sb.Append(column.ColumnName + ',');
}
//append a carriage return
sb.Append("\r\n");
//loop thru each row of our datatable
foreach (DataRow row in dataTable.Rows)
{
//loop thru each column in our datatable
foreach (DataColumn column in dataTable.Columns)
{
//get the value for tht row on the specified column
// and append our separator
sb.Append(row[column].ToString() + ',');
}
//append a carriage return
sb.Append("\r\n");
}
}
//return our values
return sb.ToString();
}
everything just copied from here: http://forums.asp.net/t/1115305.aspx you should be good to go with a little exercise of conversion C# -> VB.NET ;-)

Resources