Export to Excel - How to dynamically set header text using LINQ? - c#

My below code is working well except for one slight issue. When I open the excel sheet, the column headers are pulling directly from the code below I.E.data.FleetNumber displays as FleetNumber for the column header.
Is it possible to overwrite this? E.G I want it to display Fleet No.
I've done a lot of searching but I cant find an answer. Any help is appreciated.
public void ExportToBeDoneVehiclesToExcel()
{
int count = 10;
var grid = new System.Web.UI.WebControls.GridView();
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
var list = vehicleBusinessLogic.GetToBeDoneVehicles(count);
grid.DataSource = from data in list
select new
{
data.RegistrationID,
data.FleetNumber,
data.VIN,
data.LocationDescription,
data.ServiceDescription,
data.NextInspectionDueDate
};
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=Exported_ToBeDoneVehicles.xls");
Response.ContentType = "application/excel";
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

i can't test this but it seems logical to me
try specifying the variables names in the list
grid.DataSource = from data in list
select new
{
Reg = data.RegistrationID,
FleetNumber = data.FleetNumber,
VIN = data.VIN,
LocationDescription = data.LocationDescription,
ServiceDescription = data.ServiceDescription,
NextInspectionDueDate = data.NextInspectionDueDate
};

Related

getting issue using OpenXML

While creating an Excel document at runtime I get the following error:
Excel found unreadable content in 'Filename.xlsx'. Do you want to
recover the content of this workbook? If you trust the source of this
workbook, Click yes.
I have seen many posts regarding this on stack overflow but they have not helped me in this situation.
Below is my C# code which (attempts to) create the excel file:
var workbook = new XLWorkbook();
System.Data.DataTable Table = new System.Data.DataTable();
string AdvId = GlobalEntityID + "-" + AyId + "-" + QtrID;
var CSRExpenditureData = objCsrExp.GetCSRExpendituresFromSP(AdvId); //Get data in list from sp
Table = ListToDataTable(CSRExpenditureData); //Convert list to datatable
Table.Columns.Remove("ID"); //Remove extra columns
Table.Columns.Remove("IsActive"); //Remove extra columns
Table.Columns.Remove("IsDefault"); //Remove extra columns
Table.Columns.Remove("IsSubmit"); //Remove extra columns
if (Table.Columns.Count > 0)
{
var ws = workbook.Worksheets.Add(Table, ReportName);
}
workbook.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
workbook.Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=" + ReportName + ".xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
workbook.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
}
Note : Please don't mark this as duplicate because I have tried other posts as well

Export a gridview to Excel with page orientation set to landscape?

Haven't found any good solution to export a GridView to Excel with following options :
Page orientation set to Landscape
Margins Normal
All columns fit to one page
Existing code to export to Excel is as follows
private void ExportToExcel(GridView grdGridView)
{
DataTable dt = Whatever();
grdGridView.AllowPaging = false;
grdGridView.Columns[13].Visible = false;
grdGridView.DataSource = dt;
grdGridView.DataBind();
string attachment = "attachment; filename=ExcelSheet1.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm(); // Create a form to contain the grid
grdGridView.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(grdGridView);
frm.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
}
What could be the best possible way to export to Excel in order to achieve all of this? Do I need to use some library or some other tool like report viewer? Is it possible or not?
Found the solution
Download epplus library.
using OfficeOpenXml;
private void ExportToExcel()
{
using (ExcelPackage objExcelPackage = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet objWorksheet = objExcelPackage.Workbook.Worksheets.Add("ExcelSheet1");
DataTable dtQuoteComparison = dt //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
objWorksheet.Cells["A1"].LoadFromDataTable(dt, true);
var start = objWorksheet.Dimension.Start;
var end = objWorksheet.Dimension.End;
for (int row = start.Row+1; row <= end.Row; row++) //iterate through rows
{
objWorksheet.Cells[rowStart, colStart, rowEnd,colEnd].WhateverProperty=value;
}
objWorksheet.PrinterSettings.Orientation = eOrientation.Landscape;
objWorksheet.PrinterSettings.FitToWidth = 1;
//Write it back to the client
if (System.IO.File.Exists(filepath))
System.IO.File.Delete(filepath);
//Create excel file on physical disk
FileStream objFileStrm = System.IO.File.Create(filepath);
objFileStrm.Close();
//Write content to excel file
System.IO.File.WriteAllBytes(filepath,objExcelPackage.GetAsByteArray());
}
}
Now the problem I am facing is that All columns fit to one page is not working even after setting
objWorksheet.PrinterSettings.FitToWidth = 1;

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

How to Display the Data have more than two spaces in Repeater?

I got the data from database into my dataset is and then i bind into my repeater control but its is been showing like "Prince Antony G". It eliminated the Spaces.
and also i export those data into excel, In excel also the spaces were removed.
I need the show data whatever in my Database. Any idea to solve this problem.
In stack overflow Question box also remove more spaces in between two words
My Excel Coding:
DataTable dt = new DataTable("Report");
DataRow dr;
dt.Columns.Add("Name");
for (int i = 0; i < dt_Status.Rows.Count; i++)
{
dr = dt.NewRow();
dr["Name"] ="<pre>"+ dt_Status.Rows[i]["NAME"].ToString() +"</pre>";
dt.Rows.Add(dr);
}
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";
response.AddHeader("Content-Disposition", "attachment;filename=Report.xls");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
After updating my code i got the excel output as:
I need to display in a single cell.
html doesn't recognize multiple spaces.
You you put your data between <pre></pre> tags to say that is is per-formatted.
Or you could replace the space with . This is a non breaking space character.
Space is used for formatting your html code, and hence if you have more than one space, it gets wrapped to just one.
A simple handy stuff:
string value = String.Join(" ", "Prince Antony G".Split(new char[] {' '},
StringSplitOptions.RemoveEmptyEntries));

Exporting gridview to .xls

I am working on a web page which has a gridview control. I need the data to be transferred to .xls format. I am able to create the .xls file and transfer the data, but the problem is that I need the gridcells to be displayed in the background in the excel sheet. Right now, it is only showing a blank background without the gridcells. Otherwise the gridview is getting transferred fine. Due to this issue, printing the .xls file is a problem. Tables with more columns are not compressing, but getting printed over 2-3 pages. My code is as follows:
public static void ExportToXLS(string fileName, GridView gv,string companyName,string reportTitle , string period)
{
//For writing to XLS file
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
Table tableReport = new Table();
tableReport.GridLines = gv.GridLines;
// add the header row to the table
if (gv.HeaderRow != null)
{
ReportList.PrepareControlForExport(gv.HeaderRow);
tableReport.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
ReportList.PrepareControlForExport(row);
tableReport.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
ReportList.PrepareControlForExport(gv.FooterRow);
tableReport.Rows.Add(gv.FooterRow);
}
//Takes value of company name
System.Web.UI.WebControls.Label labelCompany = new System.Web.UI.WebControls.Label();
labelCompany.Text = companyName;
labelCompany.Font.Bold = true;
//Takes value of report title
System.Web.UI.WebControls.Label labelReport = new System.Web.UI.WebControls.Label();
labelReport.Text = reportTitle;
labelReport.Font.Bold = true;
//Takes value of report period
System.Web.UI.WebControls.Label labelPeriod = new System.Web.UI.WebControls.Label();
labelPeriod.Text = period;
// render the htmlwriter into the response
htw.Write("<center>");
labelCompany.RenderControl(htw);
htw.Write("<br/>");
labelReport.RenderControl(htw);
htw.Write("<br/>");
labelPeriod.RenderControl(htw);
htw.Write("</center>");
htw.Write("<br/>");
tableReport.RenderControl(htw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
Any suggestions?
Ref: Export grid
Try this:
protected void btnExportExcel_Click(object sender, EventArgs e)
{
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);
grdExport.AllowPaging = false;
oMailing.GetData(out ODs);
grdExport.DataSource = ODs;
grdExport.DataBind();
//Change the Header Row back to white color
grdExport.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Apply style to Individual Cells
grdExport.HeaderRow.Cells[0].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[1].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[2].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[3].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[4].Style.Add("background-color", "green");
grdExport.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();
}
All of the answers will get you what you want - you're just missing the formatting part.
At the end of the day, what you are really creating is an HTML file (with an HTML Table) that Excel can read. The RESPONSE headers in #BhaskarreddyMule is what "forces" the client to treat the file as an "xls" file and if it has Excel run and open it (but the bottom line is that its not really a "native" Excel file.
Now that's out of the way, think in HTML. Style your columns, rows, and text content as you would in HTML. That's how you'd control the format (i.e. old school "nowrap" to prevent wrapping cell content, font-size, etc. etc.).
I haven't done this in a while (I've moved on to Excel XML and VB.Net XML literals when I need to do this) so I'm not sure how much level of control you have with RenderControl...or if you have to go even further "old school" and build the HTML table string from scratch.....
First of all Refer this: How to export nested gridview to excel/word with gridlines on the child grid, Hope it will help you to solve your problem.
Ref: How to export gridview to excel in a console type application?
You can refer to the Export To Excel control in the below link. It’s a custom control. Hope it can help you.
http://exporttoexcel.codeplex.com/
Styling exported grid:
protected void btnExportExcel_Click(object sender, EventArgs e)
{
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);
grdExport.AllowPaging = false;
oMailing.GetData(out ODs);
grdExport.DataSource = ODs;
grdExport.DataBind();
//Change the Header Row back to white color
grdExport.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Apply style to Individual Cells
grdExport.HeaderRow.Cells[0].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[1].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[2].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[3].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[4].Style.Add("background-color", "green");
for (int i = 0; i < grdExport.Rows.Count; i++)
{
GridViewRow row = grdExport.Rows;
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
row.Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
row.Cells[3].Style.Add("background-color", "#C2D69B");
row.Cells[4].Style.Add("background-color", "#C2D69B");
}
}
grdExport.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();
}
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);
I tried with the export to excel, seems that you first need to create an using part Excel = using Microsoft.Office.Interop.Excel, when u click on the button, just create an excel class having workbook and worksheet property and then using gridview property of Gridview.Row[].cell[].Text., u can dynamically store every value in the gridview to the worksheet and then write it to a FILE....

Categories