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();
}
Related
I am exporting data with images to Excel by using the following code.
Code
protected void ExportToExcel(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = "select CustomerID, ContactName, City, PostalCode, display_picture" +
" from customers";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//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";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i .textmode { mso-number-format:\#; } ";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
The Excel is downloading properly. But the problem is when I am filtering the data in the Excel. The images in the Excel are in Move but don't size with cells property. How to make the images with the property, Move and size with cells?
Your code doesn't create an Excel file at all, it creates an HTML table and sends it with a fake content type, that of the old binary Excel format (xls). Excel isn't fooled, it detects that this is an HTML table and tries to import it using default settings. This can break for any number of reasons.
It's far easier and cheaper to create a real Excel file with a library like EPPlus. For starters, you can fill a sheet directly from a DataTable :
protected void ExportToExcel(object sender, EventArgs e)
{
///...
DataTable dt = GetData(cmd);
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
var ws = pck.Workbook.Worksheets.Add("Demo");
//Load the datatable into the sheet, starting from cell A1.
//Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(dt, true);
//That's it!
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
}
You can add pictures with the Drawings.AddPicture method :
ExcelPicture pic = ws.Drawings.AddPicture("pic1", new FileInfo("PathToMyImage.png"));
The result is an xlsx file which is a package of compressed XML files. This means it's actually smaller than the HTML table or CSV files that are often generated instead of actual Excel files.
EasyXLS is a library that also exports xlsx and xls files with images.
//Create a workbook
ExcelDocument workbook = new ExcelDocument();
//Add a worksheet
ExcelWorksheet worksheet = new ExcelWorksheet("Gridview");
workbook.easy_addWorksheet(worksheet);
//Add the gridview to the worksheet
DataSet dataSet = new DataSet();
dataSet.Tables.Add((DataTable)GridView1.DataSource);
worksheet.easy_insertDataSet(dataSet);
//Add an image
worksheet.easy_addImage("image.jpg", "A10");
//Exporting gridview with image
workbook.easy_WriteXLSXFile("DataTable.xlsx");
More about inserting images, you can find at:
http://www.easyxls.com/manual/basics/excel-image-import-export.html
If the image bytes are loaded from database, you will need to temporary save the image locally on machine.
You can also check how to export gridview to excel to see more about formatting the data.
I have a web application that exports data from a gridview to Excel. It works fine in Chrome but doesn't work in IE 11 and Firefox. I see a lot of issues with this when I google it but this error seems to be unique.
protected void ExportToExcel(List<MapAmericas.Model.Project> Projects)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.AddHeader("content-disposition", "attachment;filename=MyFile" + DateTime.Now.ToString() + ".xls");
Response.Charset = "";
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
this.EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
GridView gv = new GridView();
gv.AutoGenerateColumns = false;
gv.RowDataBound += new GridViewRowEventHandler(dataExportExcel_ItemDataBound);
gv.DataSource = Projects;
gv.DataBind();
gv.RenderControl(htw);
Response.Write(AddExcelStyling()); //this contains the opening html elements
StringBuilder sbResponseString = new StringBuilder();
sbResponseString.Append(sw + "</body></html>");
Response.Write(sbResponseString.ToString());
Response.Flush();
Response.Close();
Response.End();
}
...and the issue I'm getting has to do with not being able to access Temporary Internet Files. I get a popup "Problems during Load" and about a dozen entries: "Missing File...Temporary Internet Files\Content\" and then I get a message reading "Unable to read file".
I had an image to represent the error but I'm not able to upload images.
When I click on one of the links, it loads up my webpage without any styles and I don't get an excel file.
Does anyone know what the issue would be?
I got it! I added 2 lines of code to my existing code and it works. See lines marked with **:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
//HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Panorama_Project-" + DateTime.Now.ToString() + ".xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
this.EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
GridView gv = new GridView();
gv.AutoGenerateColumns = false;
gv.RowDataBound += new GridViewRowEventHandler(dataExportExcel_ItemDataBound);
gv.DataSource = Projects;
gv.DataBind();
gv.RenderControl(htw);
HttpContext.Current.Response.Write(AddExcelStyling());
StringBuilder sbResponseString = new StringBuilder();
sbResponseString.Append(sw + "</body></html>");
**HttpContext.Current.Response.AddHeader("Content-Length", sbResponseString.Length.ToString());**
HttpContext.Current.Response.Write(sbResponseString.ToString());
//HttpContext.Current.Response.Flush();
//HttpContext.Current.Response.Close();
//HttpContext.Current.Response.End();
**System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();**
It seems as though it was trying to display the entire Response object which included my page and all linked resources. The Content-Length and replacing Reponse.End and Response.Flush with System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest() seems to do the trick.
This is the simplified version of an Export To Excel function (for a datatable) that I use and one that works for all the browsers. See if this helps. The code is quite similar to yours though:
public void ExportDataToExcel(String FileName, DataTable dtData)
{
// get gridview out of datatable
GridView gv = new GridView();
gv.AllowPaging = false;
gv.DataSource = dtData;
gv.DataBind();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition",
"attachment;filename=" + FileName + ".xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < gv.Rows.Count; i++)
{
// Apply text style to each Row
gv.Rows[i].Attributes.Add("class", "textmode");
}
gv.RenderControl(hw);
HttpContext.Current.Response.Output.Write(sw.ToString());
// commenting this out to resolve this error
// System.Web.HttpException: The remote host closed the connection.
// The error code is 0x800703E3.
// HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
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
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.
I have been able to populate a repeater but the only problem I'm having is to export it to an excel sheet.
There are no data displayed in the excel file .
What I'm thinking is that because of some postback when I click the export button, the data on the repeater gets deleted or something.
Here is the code :
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
Table tb = new Table();
TableRow tr1 = new TableRow();
TableCell cell1 = new TableCell();
cell1.Controls.Add(Repeater1);
tr1.Cells.Add(cell1);
tb.Rows.Add(tr1);
tb.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
For exporting data in Excel format I would recommend using EPPlus library instead of writing strings.
EPPlus is a .net library that reads and writes Excel 2007/2010 files
using the Open Office Xml format (xlsx).
EPPlus supports: Cell Ranges, Cell styling (Border, Color, Fill, Font,
Number, Alignments), Charts, Pictures, Shapes, Comments, Tables,
Protection, Encryption, Pivot tables, Data validation
I think "Repeater1" and table "tb" must be attached to Page (Page.Controls.Add(tb)).
Try to:
render controls to string var rendered=RenderControlToString(tb);
then clear response Response.Clear();
then write rendered string Response.Write(rendered);
public static string RenderControlToString(Control c)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
c.RenderControl(htmlWriter);
sw.Close();
htmlWriter.Close();
return sb.ToString();
}