Add Title before Export Excel - asp.net

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>")

Related

how to display image from database to image control in asp.net

i want to retrieve image from database but this code did not display any thing.
image data type in database is image.I dont know what is wrong with this code
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Session["pro_ID"]);
int id = Convert.ToInt32(Session["pro_id"]);
SqlConnection conn = new SqlConnection("Data source=DESKTOP-QPTTS3M;initial catalog=shopolic;integrated security=True;");
conn.Open();
SqlCommand cmd = new SqlCommand("spgetimage", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter() { ParameterName = "#id", Value = Session["pro_id"] };
cmd.Parameters.Add(param);
//cmd.ExecuteScalar();
SqlCommand cmd2 = new SqlCommand("select *from product where product_ID='" + Session["pro_id"] + "'", conn);
// cmd2.ExecuteNonQuery();
SqlDataReader dr = cmd2.ExecuteReader();
if (dr.Read())
{
name.Text = dr["name"].ToString();
byte[] img = (byte[])(dr["image"]);
if (img == null)
{
Image1.ImageUrl = "~/Images/bg.png";
}
else
{
string base64String = Convert.ToBase64String(img);
Image1.ImageUrl = String.Format("data:image/jpg;base64,{0}", base64String);
// MemoryStream ms = new MemoryStream(img);
}
}
// byte[] bytes = (byte[])cmd.ExecuteScalar();
// string strbase64 = Convert.ToBase64String(bytes);
//Image1.ImageUrl = "data:Image/png;base64,"+strbase64;
//SqlDataReader dr = cmd.ExecuteReader();
//DataTable DT = new DataTable();
conn.Close();
}

Unable to do search for selected items

I am using this code to search for selected items inside a checkbox list and it doesn't work.
protected void btnSearchCode_Click(object sender, ImageClickEventArgs e)
{
string selectedValues = string.Empty;
foreach (ListItem item in cblCode.Items)
{
if (item.Selected)
selectedValues += item.Value + ",";
}
if (selectedValues != string.Empty)
selectedValues = selectedValues.Remove(selectedValues.Length - 1);
cblCode.DataSource = DataReport.SearchCode(selectedValues);
cblCode.DataBind();
}
public static DataTable SearchCode(string selectedValues)
{
string strcon = ConfigurationManager.ConnectionStrings["LocalDB"].ConnectionString;
DataTable datatable = new DataTable();
using (SqlConnection conn = new SqlConnection(strcon))
{
conn.Open();
SqlCommand command = new SqlCommand();
string strQuery = "Select Group, Name from Details where Code in (" + selectedValues + ")", conn;
command.Connection = conn;
SqlDataAdapter dataadapter = new SqlDataAdapter();
dataadapter.SelectCommand = command;
DataSet ds = new DataSet();
dataadapter.Fill(datatable);
}
return datatable;
}
Really appreciate any help on this.
You have not used strQuery at all.
Try this :
public static DataTable SearchCode(string selectedValues)
{
string strcon = ConfigurationManager.ConnectionStrings["LocalDB"].ConnectionString;
DataTable datatable = new DataTable();
using (SqlConnection conn = new SqlConnection(strcon))
{
conn.Open();
string strQuery = "Select Group, Name from Details where Code in (" + selectedValues + ")";
SqlCommand command = new SqlCommand(strQuery, conn);
SqlDataAdapter dataadapter = new SqlDataAdapter();
dataadapter.SelectCommand = command;
DataSet ds = new DataSet();
dataadapter.Fill(datatable);
}
return datatable;
}
You create the query string but you never assign it to the command variable. Therefore, when you assign it to selectCommand, there isn't anything to query from DB. You want to add this line of code to assign the query string to variable:
command = new SqlCommand(strQuery,conn);
Always Use SqlParamerter while passing parameters to the database
i think You are missing single inverted comma because Your SeletedValues is string
string strQuery = "Select Group, Name from Details
where Code in ('" + selectedValues + "')", conn;

Export data into Excel, Word and PDF with Formatting

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

How to populate the excelsheetcloumn names into a dropdown list?

Hi i have an excel sheet with headers,i want to populate those headers into a dropdown list...
can any one help me with the select statement and procedure
i am working on a code i dnt know whether its correct or not
DropDownList list = new DropDownList();
string connectionstring = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", Excelpath);
string query1 = String.Format("select * from [{0}]", DDlist.SelectedItem.Text);
// OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query1, connectionstring);
using (OleDbConnection conn1 = new OleDbConnection(connectionstring))
{
OleDbCommand odc1 = new OleDbCommand(string.Format(query1, conn1));
conn1.Open();
OleDbDataReader dr;
dr = odc1.ExecuteReader();
while (dr.Read())
{
list.Items.Add(dr[column.ColumnName].ToString());
}
dr.Close();
conn1.Close();
}
in this method i am geting an error at this line
dr = odc1.ExecuteReader();Error:ExecuteReader: Connection property has not been initialized.
can any one help mw with this, thanks in advance
try this it may work.....
foreach (DataTable table in DS.Tables)
{
foreach (DataColumn column in table.Columns)
{
DropDownList list = new DropDownList();
string connectionstring = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", Excelpath);
string query1 = String.Format("select * from [{0}]", DDlist.SelectedItem.Text);
using (OleDbConnection conn1 = new OleDbConnection(connectionstring))
{
OleDbCommand odc1 = new OleDbCommand(query1, conn1);
conn1.Open();
DataTable dte = null;
DataSet ds = new DataSet();
dte = conn1.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = odc1;
objAdapter1.Fill(ds, "xldata");
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
list.Items.Add(ds.Tables[0].Columns[i].ColumnName.ToString());
}
conn1.Close();
}
I think you are not passing Connection to OleDBCommand. So try,
OleDbCommand odc1 = new OleDbCommand(query1, conn1);
The OleDbCommand class has two main parameters to be passed for a proper execution. That are Query and connection object. In your code you are passing the connection, but it is placed inside the String.Format(), so place it outside. See the code below....
OleDbCommand odc1 = new OleDbCommand(string.Format(query1, conn1));
TO
OleDbCommand odc1 = new OleDbCommand(query1, conn1);

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