Export excel from data table using Open sdk xml - asp.net

I am exporting data in to excel using open xml sdk. Now i want that data directly export using data table not by using grid view when i give data table directly into wb.Worksheets.Add(dt) it give worksheets name exception,secondly i want to save file into some location rather than downloading my code is below.
DataTable dt = new DataTable("GridView_Data");
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (GridViewRow row in GridView1.Rows)
{
dt.Rows.Add();
for (int i = 0; i < row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text;
}
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}

Related

HtmlTextWriter to export gridview to excel is generating blank space in excel

enter image description here
I am getting gridview data dispayed as shown in the image where all other cells which do not have any data are coming as completely blank white page rather than excel sheet. How will I get excel sheet for the rest of the space?
Response.Buffer = true;
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=PMSUptimeReport.xls");
//string style = #"<style> td { mso-number-format:\#;} </style>";
//Response.Write(style);
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.HeaderRow.Style.Add("color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
{
//Change to Blue
gv.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
}
int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in gv.Rows)
{
gvrow.BackColor = Color.Aqua;
if (j <= gv.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();[enter image description here][2]`

Export GridView to Existing Excel as New Sheet

I have GridView in my web application, while click the Export button the value from gridview to be export into new sheet in existing excel file accordingly as Day1, Day2, ...
Thanks!!!
You can use EPPlus Library for this, here's a quick snippet on how to create sheets:
string filePath = "~/App_Data/emptyExcelFile.xlsx";
FileInfo fi = new FileInfo(Server.MapPath(filePath));
using (ExcelPackage xlPackage = new ExcelPackage(fi))
{
for (int i = 1; i <= 3; i++)
{
ExcelWorksheet worksheet;
worksheet = xlPackage.Workbook.Worksheets.Add("Day"+i, sheetName);
}
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=" + "myExcelFile.xlsx");
Response.BinaryWrite(xlPackage.GetAsByteArray());
Response.Flush();
Response.End();
}
Hope this helps.

Export data table to Excel sheet

I want to export data from data table to Excel file. I need to save the file on server. I am using the console application for this project.
Since you haven't mentioned if excel is installed, i recommend EPPlus to create the excel file. It has a convenient method LoadFromDataTable:
using (var pck = new ExcelPackage())
{
var ws = pck.Workbook.Worksheets.Add("Worksheet-Name");
ws.Cells["A1"].LoadFromDataTable(dataTable1, true, OfficeOpenXml.Table.TableStyles.Medium1);
using(var fileStream = File.Create(path))
pck.SaveAs(fileStream);
}
Edit i've only just seen that you have tagged export-to-csv.
var lines = dataTable1.AsEnumerable()
.Select(r => string.Join(",", r.ItemArray));
string csv = string.Join(Environment.NewLine, lines);
File.AppendAllText(path, csv);
if (DtReqDetails != null)
{
string attachment = "attachment; filename=History.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in DtReqDetails.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in DtReqDetails.Rows)
{
tab = "";
for (i = 0; i < DtReqDetails.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
If you are using MS SQL, then they have a built-in procedure for exporting a table to an Excel spreadsheet. No coding required.

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.

how to Design the exported excel in asp.net?

I am exporting gridview data to excel but that excel file add the some lable text and textbox values and format also taken , pls give how to design the excel code in asp.net. I am writing like this
All gridview data taken dataset ds
-pls give me textbox values and some label or normal text designed code in excel
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = ds;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=DataTable.xls");
Response.Charset = string.Empty;
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
////Apply text style to each Row
GridView1.Rows[i].Cells[4].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:'\#,\#\#0\.00';}
.textmode1(mso-number-format:'\#';}
.SSNmode{mso-number-format:'000-00-000';} </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
Take a look at this awesome tool: http://www.carlosag.net/Tools/ExcelXmlWriter/
Futhermore, the author also created a code generator, which generates .net code from a provided excel sheet(formatting, layout and so on)
http://www.carlosag.net/Tools/ExcelXmlWriter/Generator.aspx
Here's some code that generates an excel file from a datatable (converted vb code, as pr. request by poster)
CarlosAg.ExcelXmlWriter.Workbook book = new CarlosAg.ExcelXmlWriter.Workbook();
book.ExcelWorkbook.ProtectWindows = false;
book.ExcelWorkbook.ProtectStructure = false;
var styles = book.Styles;
WorksheetStyle defaultStyle = styles.Add("Default");
var defStyles = defaultStyle;
defStyles.Name = "Normal";
defStyles.Font.FontName = "Calibri";
defStyles.Font.Size = 11;
defStyles.Font.Color = "#000000";
defStyles.Alignment.Vertical = StyleVerticalAlignment.Bottom;
Worksheet sheet = book.Worksheets.Add("Sheet1");
sheet.Table.DefaultRowHeight = 15f;
sheet.Table.FullColumns = 1;
sheet.Table.FullRows = 1;
DataTable dt = new DataTable(); //= your datatable
//Header
WorksheetRow HeaderRow = sheet.Table.Rows.Add();
foreach (DataColumn col in dt.Columns)
{
HeaderRow.Cells.Add(col.ColumnName.ToString());
}
//Body
foreach (DataRow dr in dt.Rows)
{
WorksheetRow row = sheet.Table.Rows.Add();
foreach (DataColumn cols in dt.Columns)
{
row.Cells.Add(dr[cols.ColumnName.ToString()].ToString());
}
}
sheet.Options.Selected = true;
sheet.Options.ProtectObjects = false;
sheet.Options.ProtectScenarios = false;
book.Save("path to file");

Resources