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.
Related
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();
}
}
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();
}
How would one go about saving a dataset as a CSV file to a client pc?
I Can save a file from the server to a client pc, and I can convert a Datatable to a CSV file, but I cant seem to figure out how to put the two together.
Save file from server to client (as attachment)
String FileName = "my file name";
String FilePath = #"C:\testfile.txt";
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath + FileName); //Can only put the file path in here, cant put the datatable or convertion in there..
response.Flush();
response.End();
Convert datatable to CSV file (since I have a datatable that should be saved as a CSV file to the client pc)
StringBuilder sb = new StringBuilder();
string[] columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
string[] fields = row.ItemArray.Select(field => field.ToString()).
ToArray();
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText("test.csv", sb.ToString());
You use the response.Write(sb.ToString()); and not the response.TransmitFile to render to the output yours CSV generated data. For example:
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=DownloadedData.txt;");
StringBuilder sb = new StringBuilder();
string[] columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
string[] fields = row.ItemArray.Select(field => field.ToString()).
ToArray();
sb.AppendLine(string.Join(",", fields));
}
// the most easy way as you have type it
response.Write(sb.ToString());
response.Flush();
response.End();
and is better to use a handler, and not do that from the page.
Instead of writing to File object, write to Response object. When you will say "Response.End();", it will prompt to save the file
U can try this code, this creates an xls file as an attachment
Response.AppendHeader("content-disposition", "attachment;filename=FileEName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
this.EnableViewState = false;
Response.Write("PASS YOUR STRING HERE");
Response.End();
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.
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.