whats the best way to export a Datagrid to excel? I have no experience whatsoever in exporting datagrid to excel, so i want to know how you guys export datagrid to excel.
i read that there are a lot of ways, but i am thinking to just make a simple export excel to datagrid function.i am using asp.net C#
cheers..
The simplest way is to simply write either csv, or html (in particular, a <table><tr><td>...</td></tr>...</table>) to the output, and simply pretend that it is in excel format via the content-type header. Excel will happily load either; csv is simpler...
Here's a similar example (it actually takes an IEnumerable, but it would be similar from any source (such as a DataTable, looping over the rows).
public static void WriteCsv(string[] headers, IEnumerable<string[]> data, string filename)
{
if (data == null) throw new ArgumentNullException("data");
if (string.IsNullOrEmpty(filename)) filename = "export.csv";
HttpResponse resp = System.Web.HttpContext.Current.Response;
resp.Clear();
// remove this line if you don't want to prompt the user to save the file
resp.AddHeader("Content-Disposition", "attachment;filename=" + filename);
// if not saving, try: "application/ms-excel"
resp.ContentType = "text/csv";
string csv = GetCsv(headers, data);
byte[] buffer = resp.ContentEncoding.GetBytes(csv);
resp.AddHeader("Content-Length", buffer.Length.ToString());
resp.BinaryWrite(buffer);
resp.End();
}
static void WriteRow(string[] row, StringBuilder destination)
{
if (row == null) return;
int fields = row.Length;
for (int i = 0; i < fields; i++)
{
string field = row[i];
if (i > 0)
{
destination.Append(',');
}
if (string.IsNullOrEmpty(field)) continue; // empty field
bool quote = false;
if (field.Contains("\""))
{
// if contains quotes, then needs quoting and escaping
quote = true;
field = field.Replace("\"", "\"\"");
}
else
{
// commas, line-breaks, and leading-trailing space also require quoting
if (field.Contains(",") || field.Contains("\n") || field.Contains("\r")
|| field.StartsWith(" ") || field.EndsWith(" "))
{
quote = true;
}
}
if (quote)
{
destination.Append('\"');
destination.Append(field);
destination.Append('\"');
}
else
{
destination.Append(field);
}
}
destination.AppendLine();
}
static string GetCsv(string[] headers, IEnumerable<string[]> data)
{
StringBuilder sb = new StringBuilder();
if (data == null) throw new ArgumentNullException("data");
WriteRow(headers, sb);
foreach (string[] row in data)
{
WriteRow(row, sb);
}
return sb.ToString();
}
You can do it in this way:
private void ExportButton_Click(object sender, System.EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.ClearControls(dataGrid);
dataGrid.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
Complete example here.
SpreadsheetGear for .NET will do it.
You can see live ASP.NET samples with C# and VB source code here. Several of these samples demonstrate converting a DataSet or DataTable to Excel - and you can easily get a DataSet or DataTable from a DataGrid. You can download the free trial here if you want to try it yourself.
Disclaimer: I own SpreadsheetGear LLC
Related
I tried to export the dataset which have 2 tables to the excel sheet, unfortunately I can't.
I have code to export data table to excel. So instead of dataset, I called the ExportToExcel function which I have in my code to export datatable to excel 4 times. But once it created the first sheet, it stops the control flow. Control doesn't call the second function
ExportToExcel(getReports.Tables[1], "ConsumerBookedSlots");
Here is the code:
public ActionResult GetCuratorsAvailability(string availabilitydate)
{
string fromDate = "";
string endDate = "";
if (availabilitydate != "")
{
fromDate = availabilitydate.Split('-')[0];
endDate = availabilitydate.Split('-')[1];
if (DateTime.Parse(endDate) >= DateTime.Parse(fromDate))
{
DataSet getReports = AdminBLL.GetCuratorsAvailability(fromDate, endDate);
ExportToExcel(getReports.Tables[0], "CuratorsAvailableSlots");
ExportToExcel(getReports.Tables[1], "ConsumerBookedSlots");
}
}
return View("Reports");
}
public void ExportToExcel(DataTable dt, string FileName)
{
if (dt.Rows.Count > 0)
{
if (System.Web.HttpContext.Current.Response.RedirectLocation == null)
{
string filename = FileName + ".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();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.ContentType = "application/vnd.ms-excel";
Response.Write(tw.ToString());
Response.Flush();
Response.End();
}
}
}
I am unable to download getReports.Tables[1] data because I am getting this error:
server cannot append header after http headers have been sent. mvc
And it is downloading firstfile after error in the browser.
After the download of the first file, the execution hits this line-
Response.End();
That means, the response is ended, and headers have been sent to the client. There's no way you can initiate the download of the second file. If you want to download multiple files in a single button click, you need to zip it into one, and then initiate the download.
To zip the files you can do this-
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}
Snippet from here.
If you want to make both excel spreadsheets a part of single excel document by putting each one of them as a worksheet, you can use ClosedXML.
I've used ClosedXML (an OpenXML implementation) several times, including in an ASP.NET MVC application and it works like a charm.
Exporting data is a breeze:
using (var memoryStream = new MemoryStream())
{
using (XLWorkbook workbook = new XLWorkbook())
{
using (IXLWorksheet worksheet = workbook.AddWorksheet("WorksheetName"))
{
var toExport = GetData();
worksheet.Row(1).Style.Font.Bold = true;
worksheet.Cell(1, 1).Value = "Column 1";
worksheet.Cell(1, 2).Value = "Column 2";
worksheet.Cell(1, 3).Value = "Column 3";
// Export the data and set some properties
worksheet.Cell(2, 1).Value = toExport.AsEnumerable();
worksheet.RangeUsed().SetAutoFilter();
worksheet.Columns().AdjustToContents();
workbook.SaveAs(memoryStream);
memoryStream.Position = 0;
return File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "filename.xlsx");
}
}
}
I'm trying to export data as a CSV file in C#, but the problems starts when i'm trying to import the csv file in excel.
In excel I'm using the function "import from text", and afterwards I set the delimiter to semicolon
My problem is that some of the columns have linebreaks and then the import in excel is wrong.
I have tried with single and doubles quotes with no luck.
I have searched for a solution, but has not found one yet.
Anyone knows if lumenworks has a export function, because i'm using this for the import function
The problem is the export function and the linebreaks are required.
if (list.Any())
{
result = list.Select(i => new
{
i.Product.ProductIdentifier,
i.Product.Header,
body = string.Format("\"" + "{0}" + "\"", i.Product.Body),
Active = i.Product.Active ? 1 : 0,
Approved = i.Product.Approved ? 1 : 0,
i.Product.Sort,
i.Product.MetaDescription,
i.Product.MetaKeywords,
i.CatalogMenuItemContentItemId
}).ToList().ToCsv(";");
}
string attachment = "attachment; filename=myfile.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
HttpContext.Current.Response.Write(result);
HttpContext.Current.Response.End();
public static string ToCsv<T>(this IEnumerable<T> items, string seperator = ",")
where T : class
{
var csvBuilder = new StringBuilder();
var properties = typeof(T).GetProperties();
foreach (T item in items)
{
string line = string.Join(seperator, properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray());
csvBuilder.AppendLine(line);
}
return csvBuilder.ToString();
}
private static string ToCsvValue<T>(this T item)
{
return string.Format("{0}", HttpUtility.HtmlDecode(item.ToString()));
}
Any idea ?
whats the best way to export a Datagrid to excel? I have no experience whatsoever in exporting datagrid to excel, so i want to know how you guys export datagrid to excel.
i read that there are a lot of ways, but i am thinking to just make a simple export excel to datagrid function.i am using asp.net C#
cheers..
The simplest way is to simply write either csv, or html (in particular, a <table><tr><td>...</td></tr>...</table>) to the output, and simply pretend that it is in excel format via the content-type header. Excel will happily load either; csv is simpler...
Here's a similar example (it actually takes an IEnumerable, but it would be similar from any source (such as a DataTable, looping over the rows).
public static void WriteCsv(string[] headers, IEnumerable<string[]> data, string filename)
{
if (data == null) throw new ArgumentNullException("data");
if (string.IsNullOrEmpty(filename)) filename = "export.csv";
HttpResponse resp = System.Web.HttpContext.Current.Response;
resp.Clear();
// remove this line if you don't want to prompt the user to save the file
resp.AddHeader("Content-Disposition", "attachment;filename=" + filename);
// if not saving, try: "application/ms-excel"
resp.ContentType = "text/csv";
string csv = GetCsv(headers, data);
byte[] buffer = resp.ContentEncoding.GetBytes(csv);
resp.AddHeader("Content-Length", buffer.Length.ToString());
resp.BinaryWrite(buffer);
resp.End();
}
static void WriteRow(string[] row, StringBuilder destination)
{
if (row == null) return;
int fields = row.Length;
for (int i = 0; i < fields; i++)
{
string field = row[i];
if (i > 0)
{
destination.Append(',');
}
if (string.IsNullOrEmpty(field)) continue; // empty field
bool quote = false;
if (field.Contains("\""))
{
// if contains quotes, then needs quoting and escaping
quote = true;
field = field.Replace("\"", "\"\"");
}
else
{
// commas, line-breaks, and leading-trailing space also require quoting
if (field.Contains(",") || field.Contains("\n") || field.Contains("\r")
|| field.StartsWith(" ") || field.EndsWith(" "))
{
quote = true;
}
}
if (quote)
{
destination.Append('\"');
destination.Append(field);
destination.Append('\"');
}
else
{
destination.Append(field);
}
}
destination.AppendLine();
}
static string GetCsv(string[] headers, IEnumerable<string[]> data)
{
StringBuilder sb = new StringBuilder();
if (data == null) throw new ArgumentNullException("data");
WriteRow(headers, sb);
foreach (string[] row in data)
{
WriteRow(row, sb);
}
return sb.ToString();
}
You can do it in this way:
private void ExportButton_Click(object sender, System.EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.ClearControls(dataGrid);
dataGrid.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
Complete example here.
SpreadsheetGear for .NET will do it.
You can see live ASP.NET samples with C# and VB source code here. Several of these samples demonstrate converting a DataSet or DataTable to Excel - and you can easily get a DataSet or DataTable from a DataGrid. You can download the free trial here if you want to try it yourself.
Disclaimer: I own SpreadsheetGear LLC
I can export my radgrid to an excel file but I want to add some more info into the sheet.
If it is possible, I would appreciate for a tutorial/sample code for doing a custom excel file generation.
<tel:radgrid runat="server" id="mygrid" skinid="RadGrid_Search_Standard">
<ExportSettings HideStructureColumns="true" />
</tel:radgrid>
Grid is databound with some datatable and I need to add some data
to add some strings above
mygrid.MasterTableView.ExportToWord()
Here's some code that I use with a Telerik Grid, rather than using the ExportToExcel function they've provided I created my own button that fires it's own export event.
I have a function (not included) called getDataSource that I use to populate the grid, you could override this or create your own to fetch the data into a DataTable and add any rows/columns/data as you see fit.
//export button calls this
private void ExportReport()
{
SetPublicVariables();
System.Data.DataTable dt = GetDataSource(false);
string exportData = buildCSVExportString(dt);
string filename = string.Format("{0} - {1}.csv",
(Master as MasterPages.Drilldown).Titlelbl.Text, CampaignTitle);
if (filename.Length > 255) filename = filename.Substring(0, 255);
ExportCSV(exportData, filename);
}
//build a string CSV
public static string buildCSVExportString(DataTable exportDT)
{
StringBuilder exportData = new StringBuilder();
// get headers.
int iColCount = exportDT.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
exportData.Append(exportDT.Columns[i].ToString());
if (i < iColCount - 1)
{
exportData.Append(",");
}
}
exportData.Append(System.Environment.NewLine);
// get rows.
foreach (DataRow dr in exportDT.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
//If the variable is a string it potentially has charaters that can't be parsed properly.
//this fixes the comma issue(which adds aditional columns). Replace and escape " with "".
if (dr[i] is string)
exportData.Append(String.Format(#"""{0}""", ((string)dr[i]).Replace("\"", #"""""")));
else
exportData.Append(dr[i].ToString());
}
if (i < iColCount - 1)
{
exportData.Append(",");
}
}
exportData.Append(System.Environment.NewLine);
}
return exportData.ToString();
}
public void ExportCSV(string content, string filename)
{
filename = RemoveIllegalPathChars(filename);
HttpResponse Response = HttpContext.Current.Response;
string ext = System.IO.Path.GetExtension(filename);
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", filename));
Response.ContentType = "text/csv; charset-UTF-8;";
Response.Clear();
Response.Write(content);
Response.End();
}
A possible way would be to modify the HTML code just before exporting. Here is how.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
RadGridName.GridExporting += (s, a) =>
{
string myHtmlCode = "<span>My HTML code goes here</span>";
a.ExportOutput = a.ExportOutput.Replace("<body>", "<body>" + myHtmlCode);
};
}
This should work for both Excel (not ExcelML) and Word.
Good luck
The only thing you need to do is add your additional page info to the ExportOutput of your arg
void yourRadGridID_GridExporting(object sender, GridExportingArgs e)
{
string additionalPageInfo= "your html code for the additional page info goes here";
e.ExportOutput = e.ExportOutput.Replace("`<body>`", "`<body>`" + additionalPageInfo);
}
How can I export a dataset to file that can be opened by Excel 2003 ?
will you elaborate it ? because it is diffculties to understand the CSV/TSV
marc will u give us a sample for doing it .v now ony heard the terms csv/tsv
I think This will help you. Use http handler
<%# WebHandler Language="C#" Class="DownloadAllEvent" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.IO;
public class DownloadAllEvent : IHttpHandler
{
const int BUFFERSIZE = 1024;
public bool IsReusable
{
get
{
return true;
}
}
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
response.BufferOutput = true;
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", "attachment; filename=Events.csv");
response.Cache.SetCacheability(HttpCacheability.NoCache);
//string csvfile = request.QueryString["csvfile"];
string strNoofIds = request.QueryString["NoofIds"];
// declare variables or do something to pass parameter to writecalEntry function
writeCalEntry(response.Output, strguid, sectionid);
response.End();
}
public void writeCalEntry(TextWriter output, string[] strguid,string sectionid)
{
DataTable dt = createDataTable();
DataRow dr;
StringBuilder sbids = new StringBuilder();
// process table if neeed.. use following code to create CSV format string from table
string separator;
separator = ","; //default
string quote = "\"";
//create CSV file
//StreamWriter sw = new StreamWriter(AbsolutePathAndFileName);
//write header line
StringBuilder sb = new StringBuilder();
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
//sw.Write(TheDataTable.Columns[i]);
sb.Append(dt.Columns[i]);
if (i < iColCount - 1)
{
//sw.Write(separator);
sb.Append(separator);
}
}
//sw.Write(sw.NewLine);
sb.AppendLine();
//write rows
foreach (DataRow tempdr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(tempdr[i]))
{
string data = tempdr[i].ToString();
data = data.Replace("\"", "\\\"");
//sw.Write(quote + data + quote);
sb.Append(quote + data + quote);
}
if (i < iColCount - 1)
{
//sw.Write(separator);
sb.Append(separator);
}
}
//sw.Write(sw.NewLine);
sb.AppendLine();
}
//sw.Close();
UnicodeEncoding uc = new UnicodeEncoding();
output.WriteLine(sb);
}
public static DataTable createDataTable()
{
DataTable dt = new DataTable("EventsData");
// create tables as needed which will be converted to csv format.
return dt;
}
call this httphandler file where you want to export data in to excell format as
Response.Redirect("downloadFile.ashx");
you can send parametres also in Response.Redirect which can be fetched in .ashx file.
I think this will hepl you.
Probably the easiest route is to export individual tables as csv/tsv. The 'net is full of samples of this.
If you want to do it in 2003, you're already six years too late. ;)
If you meant something else by "2003", maybe you could clarify and people could give a better answer (although the previous answer, export as CSV, is a pretty good one).
XML Spreadsheet could be what you're looking for.
Look at this answer.
The best way that I've personally found is to use XML and the spreadsheet component.
An example code would be far too messy to post here, but start here and see where it leads:
http://msdn.microsoft.com/en-us/library/aa140062.aspx