mercredi 21 mai 2014

.net - créer Excel (.XLS et.Fichier XLSX) à partir de c# - Stack Overflow


How can I create an Excel Spreadsheet with C#?


Ideally, I would like open source so I don't have to add any third party dependencies to my code, and I would like to avoid using Excel directly to create the file (using OLE Automation.)


The .CSV file solution is easy, and is the current way I am handling this, but I would like to control the output formats.




EDIT: I am still looking at these to see the best alternative for my solution. Interop will work, but it requires Excel to be on the machine you are using. Also the OLEDB method is intriguing, but may not yield much more than what I can achieve with CSV files. I will look more into the 2003 xml format, but that also puts a > Excel 2003 requirement on the file.


I am currently looking at a port of the PEAR (PHP library) Excel Writer that will allow some pretty good XLS data and formatting and it is in the Excel_97 compatible format that all modern versions of Excel support. The PEAR Excel Writer is here: PEAR - Excel Writer




You can use a library called ExcelLibrary. It's a free, open source library posted on Google Code:


ExcelLibrary


This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that functionality in.


It's very simple, small and easy to use. Plus it has a DataSetHelper that lets you use DataSets and DataTables to easily work with Excel data.


ExcelLibrary seems to still only work for the older Excel format (.xls files), but may be adding support in the future for newer 2007/2010 formats.


You can also use EPPlus, which works only for Excel 2007/2010 format files (.xlsx files).


There are a few known bugs with each library as noted in the comments. In all, EPPlus seems to be the best choice as time goes on. It seems to be more actively updated and documented as well.


Also, as noted by @АртёмЦарионов below, EPPlus has support for Pivot Tables and ExcelLibrary may have some support (Pivot table issue in ExcelLibrary)


Here are a couple links for quick reference:
ExcelLibrary - GNU Lesser GPL
EPPlus - GNU Library General Public License (LGPL)


Here some example code for ExcelLibrary:


Here is an example taking data from a database and creating a workbook from it. Note that the ExcelLibrary code is the single line at the bottom:


//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");

//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

//Open a DB connection (in this example with OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();

//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();

adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();

//Add the table to the data set
ds.Tables.Add(dt);

//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);

Creating the Excel file is as easy as that. You can also manually create Excel files, but the above functionality is what really impressed me.




If you are happy with the xlsx format, try my codeplex project. EPPlus. Started it with the source from ExcelPackage, but today it's a total rewrite. Supports ranges, cell styling, charts, shapes, pictures, namesranges, autofilter and a lot of other stuff.




I've used with success the following open source projects:



  • ExcelPackage for OOXML formats (Office 2007)


  • NPOI for .XLS format (Office 2003). NPOI 2.0 (Alpha) also supports XLSX.



Take a look at my blog posts:


Creating Excel spreadsheets .XLS and .XLSX in C#


NPOI with Excel Table and dynamic Chart




You can use OLEDB to create and manipulate Excel files. Check this: Reading and Writing Excel using OLEDB.


Typical example:


using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\temp\\test.xls;Extended Properties='Excel 8.0;HDR=Yes'"))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("CREATE TABLE [Sheet1] ([Column1] string, [Column2] string)", conn);
cmd.ExecuteNonQuery();
}

EDIT - Some more links:





The commercial solution, SpreadsheetGear for .NET will do it.


You can see live ASP.NET (C# and VB) samples here and download an evaluation version here.


Disclaimer: I own SpreadsheetGear LLC




And what about using Open XML SDK 2.0 for Microsoft Office?


A few benefits:



  • Doesn't require Office installed

  • Made by Microsoft = decent MSDN documentation

  • Just one .Net dll to use in project

  • SDK comes with many tools like diff, validator, etc


Links:





A few options I have used:


If XLSX is a must: ExcelPackage is a good start but died off when the developer quit working on it. ExML picked up from there and added a few features. ExML isn't a bad option, I'm still using it in a couple of production websites.


For all of my new projects, though, I'm using NPOI, the .NET port of Apache POI. NPOI 2.0 (Alpha) also supports XLSX.




An extremely lightweight option may be to use HTML tables. Just create head, body, and table tags in a file, and save it as a file with an .xls extension. There are Microsoft specific attributes that you can use to style the output, including formulas.


I realize that you may not be coding this in a web application, but here is an example of the composition of an Excel file via an HTML table. This technique could be used if you were coding a console app, desktop app, or service.




You can use ExcelXmlWriter http://www.carlosag.net/Tools/ExcelXmlWriter/


It works fine.




You actually might want to check out the interop classes. You say no OLE (which this isn't), but the interop classes are very easy to use.


You might be impressed if you haven't tried them.


Please be warned of Microsoft's stance on this:



Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.





You could consider creating your files using the XML Spreadsheet 2003 format. This is a simple XML format using a well documented schema.




Here's a completely free C# library, which lets you export from a DataSet, DataTable or List<> into a genuine Excel 2007 .xlsx file, using the OpenXML libraries:


http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm


Full source code is provided - free of charge - along with instructions, and a demo application.


After adding this class to your application, you can export your DataSet to Excel in just one line of code:


CreateExcelFile.CreateExcelDocument(myDataSet, "C:\\Sample.xlsx");

It doesn't get much simpler than that...


And it doesn't even require Excel to be present on your server.




You may want to take a look at http://www.gemboxsoftware.com/GBSpreadsheetFree.htm.


They have a free version with all features but limited to 150 rows per sheet and 5 sheets per workbook, if that falls within your needs.


I haven't had need to use it myself yet, but does look interesting.




If you're creating Excel 2007/2010 files give this open source project a try: http://closedxml.codeplex.com




The various Office 2003 XML libraries avaliable work pretty well for smaller excel files. However, I find the sheer size of a large workbook saved in the XML format to be a problem. For example, a workbook I work with that would be 40MB in the new (and admittedly more tightly packed) XLSX format becomes a 360MB XML file.


As far as my research has taken me, there are two commercial packages that allow output to the older binary file formats. They are:



Neither are cheap (500USD and 800USD respectively, I think). but both work independant of Excel itself.


What I would be curious about is the Excel output module for the likes of OpenOffice.org. I wonder if they can be ported from Java to .Net.




I agree about generating XML Spreadsheets, here's an example on how to do it for C# 3 (everyone just blogs about it in VB 9 :P) http://www.aaron-powell.com/linq-to-xml-to-excel




I've just recently used FlexCel.NET and found it to be an excellent library! I don't say that about too many software products. No point in giving the whole sales pitch here, you can read all the features on their website.


It is a commercial product, but you get the full source if you buy it. So I suppose you could compile it into your assembly if you really wanted to. Otherwise it's just one extra assembly to xcopy - no configuration or installation or anything like that.


I don't think you'll find any way to do this without third-party libraries as .NET framework, obviously, does not have built in support for it and OLE Automation is just a whole world of pain.




IKVM + POI


Or, you could use the Interop ...




Here's a way to do it with LINQ to XML, complete with sample code:


Quickly Import and Export Excel Data with LINQ to XML


It's a little complex, since you have to import namespaces and so forth, but it does let you avoid any external dependencies.


(Also, of course, it's VB .NET, not C#, but you can always isolate the VB .NET stuff in its own project to use XML Literals, and do everything else in C#.)




Just want to add another reference to a third party solution that directly addresses your issue: http://www.officewriter.com


(Disclaimer: I work for SoftArtisans, the company that makes OfficeWriter)




Well,


you can also use a third party library like Aspose.


This library has the benefit that it does not require Excel to be installed on your machine which would be ideal in your case.




The Java open source solution is Apache POI. Maybe there is a way to setup interop here, but I don't know enough about Java to answer that.


When I explored this problem I ended up using the Interop assemblies.




Have you ever tried sylk?


We used to generate excelsheets in classic asp as sylk and right now we're searching for an excelgenerater too.


The advantages for sylk are, you can format the cells.




Some useful Excel automation in C# , u can find from the following link.


http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm


bolton.




Some 3rd party component vendors like Infragistics or Syncfusion provide very good Excel export capabilities that do not require Microsoft Excel to be installed.


Since these vendors also provide advanced UI grid components, these components are particularly handy if you want the style and layout of an excel export to mimic the current state of a grid in the user interface of your application.


If your export is intended to be executed server side with emphasis on the data to be exported and with no link to the UI, then I would go for one of the free open source options (e.g. ExcelLibrary).


I have previously been involved with projects that attempted to use server side automation on the Microsoft Office suite. Based on this experience I would strongly recommend against that approach.




You can create nicely formatted Excel files using this library: http://officehelper.codeplex.com/documentation
See below sample:


using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME))
{
helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;
helper.CurrentSheetName = "Sheet1";
helper.CurrentPosition = new CellRef("C3");

//the template xlsx should contains the named range "header"; use the command "insert"/"name".
helper.InsertRange("header");

//the template xlsx should contains the named range "sample1";
//inside this range you should have cells with these values:
//<name> , <value> and <comment>, which will be replaced by the values from the getSample()
CellRangeTemplate sample1 = helper.CreateCellRangeTemplate("sample1", new List<string> {"name", "value", "comment"});
helper.InsertRange(sample1, getSample());

//you could use here other named ranges to insert new cells and call InsertRange as many times you want,
//it will be copied one after another;
//even you can change direction or the current cell/sheet before you insert

//typically you put all your "template ranges" (the names) on the same sheet and then you just delete it
helper.DeleteSheet("Sheet3");
}

where sample look like this:


private IEnumerable<List<object>> getSample()
{
var random = new Random();

for (int loop = 0; loop < 3000; loop++)
{
yield return new List<object> {"test", DateTime.Now.AddDays(random.NextDouble()*100 - 50), loop};
}
}



http://www.codeproject.com/KB/cs/Excel_and_C_.aspx <= why not just use the built in power of windows, just install office on the server, any application that you install can be automated.


So much easier just use the native methods.


If it installed you can use it, this is the most awesome and under used feature in windows it was Dubbed COM back in the good old days, and it saves you tons of time and pain.


Or even easier just use the ref lib MS supplies - http://csharp.net-informations.com/excel/csharp-create-excel.htm




Look at samples how to create Excel files.


There are examples in C# and VB.NET


It manages XSL XSLX and CSV Excel files.



http://www.devtriogroup.com/ExcelJetcell/Samples





public class GridViewExportUtil
{
public static void Export(string fileName, GridView gv)
{
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))
{
// Create a form to contain the grid
Table table = new Table();

// add the header row to the table
if (gv.HeaderRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}

// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
GridViewExportUtil.PrepareControlForExport(row);
table.Rows.Add(row);
}

// add the footer row to the table
if (gv.FooterRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}

// render the table into the htmlwriter
table.RenderControl(htw);

// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}

/// <summary>
/// Replace any of the contained controls with literals
/// </summary>
/// <param name="control"></param>
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}

if (current.HasControls())
{
GridViewExportUtil.PrepareControlForExport(current);
}
}
}
}

Hi this solution is to export your grid view to your excel file it might help you out




There is a free solution to export data to excel, word, pdf without automation. http://www.codeproject.com/KB/cs/Excel_PDF_Word_ExportWiz.aspx



How can I create an Excel Spreadsheet with C#?


Ideally, I would like open source so I don't have to add any third party dependencies to my code, and I would like to avoid using Excel directly to create the file (using OLE Automation.)


The .CSV file solution is easy, and is the current way I am handling this, but I would like to control the output formats.




EDIT: I am still looking at these to see the best alternative for my solution. Interop will work, but it requires Excel to be on the machine you are using. Also the OLEDB method is intriguing, but may not yield much more than what I can achieve with CSV files. I will look more into the 2003 xml format, but that also puts a > Excel 2003 requirement on the file.


I am currently looking at a port of the PEAR (PHP library) Excel Writer that will allow some pretty good XLS data and formatting and it is in the Excel_97 compatible format that all modern versions of Excel support. The PEAR Excel Writer is here: PEAR - Excel Writer



You can use a library called ExcelLibrary. It's a free, open source library posted on Google Code:


ExcelLibrary


This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that functionality in.


It's very simple, small and easy to use. Plus it has a DataSetHelper that lets you use DataSets and DataTables to easily work with Excel data.


ExcelLibrary seems to still only work for the older Excel format (.xls files), but may be adding support in the future for newer 2007/2010 formats.


You can also use EPPlus, which works only for Excel 2007/2010 format files (.xlsx files).


There are a few known bugs with each library as noted in the comments. In all, EPPlus seems to be the best choice as time goes on. It seems to be more actively updated and documented as well.


Also, as noted by @АртёмЦарионов below, EPPlus has support for Pivot Tables and ExcelLibrary may have some support (Pivot table issue in ExcelLibrary)


Here are a couple links for quick reference:
ExcelLibrary - GNU Lesser GPL
EPPlus - GNU Library General Public License (LGPL)


Here some example code for ExcelLibrary:


Here is an example taking data from a database and creating a workbook from it. Note that the ExcelLibrary code is the single line at the bottom:


//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");

//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

//Open a DB connection (in this example with OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();

//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();

adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();

//Add the table to the data set
ds.Tables.Add(dt);

//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);

Creating the Excel file is as easy as that. You can also manually create Excel files, but the above functionality is what really impressed me.



If you are happy with the xlsx format, try my codeplex project. EPPlus. Started it with the source from ExcelPackage, but today it's a total rewrite. Supports ranges, cell styling, charts, shapes, pictures, namesranges, autofilter and a lot of other stuff.



I've used with success the following open source projects:



  • ExcelPackage for OOXML formats (Office 2007)


  • NPOI for .XLS format (Office 2003). NPOI 2.0 (Alpha) also supports XLSX.



Take a look at my blog posts:


Creating Excel spreadsheets .XLS and .XLSX in C#


NPOI with Excel Table and dynamic Chart



You can use OLEDB to create and manipulate Excel files. Check this: Reading and Writing Excel using OLEDB.


Typical example:


using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\temp\\test.xls;Extended Properties='Excel 8.0;HDR=Yes'"))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("CREATE TABLE [Sheet1] ([Column1] string, [Column2] string)", conn);
cmd.ExecuteNonQuery();
}

EDIT - Some more links:




The commercial solution, SpreadsheetGear for .NET will do it.


You can see live ASP.NET (C# and VB) samples here and download an evaluation version here.


Disclaimer: I own SpreadsheetGear LLC



And what about using Open XML SDK 2.0 for Microsoft Office?


A few benefits:



  • Doesn't require Office installed

  • Made by Microsoft = decent MSDN documentation

  • Just one .Net dll to use in project

  • SDK comes with many tools like diff, validator, etc


Links:




A few options I have used:


If XLSX is a must: ExcelPackage is a good start but died off when the developer quit working on it. ExML picked up from there and added a few features. ExML isn't a bad option, I'm still using it in a couple of production websites.


For all of my new projects, though, I'm using NPOI, the .NET port of Apache POI. NPOI 2.0 (Alpha) also supports XLSX.



An extremely lightweight option may be to use HTML tables. Just create head, body, and table tags in a file, and save it as a file with an .xls extension. There are Microsoft specific attributes that you can use to style the output, including formulas.


I realize that you may not be coding this in a web application, but here is an example of the composition of an Excel file via an HTML table. This technique could be used if you were coding a console app, desktop app, or service.



You can use ExcelXmlWriter http://www.carlosag.net/Tools/ExcelXmlWriter/


It works fine.



You actually might want to check out the interop classes. You say no OLE (which this isn't), but the interop classes are very easy to use.


You might be impressed if you haven't tried them.


Please be warned of Microsoft's stance on this:



Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.




You could consider creating your files using the XML Spreadsheet 2003 format. This is a simple XML format using a well documented schema.



Here's a completely free C# library, which lets you export from a DataSet, DataTable or List<> into a genuine Excel 2007 .xlsx file, using the OpenXML libraries:


http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm


Full source code is provided - free of charge - along with instructions, and a demo application.


After adding this class to your application, you can export your DataSet to Excel in just one line of code:


CreateExcelFile.CreateExcelDocument(myDataSet, "C:\\Sample.xlsx");

It doesn't get much simpler than that...


And it doesn't even require Excel to be present on your server.



You may want to take a look at http://www.gemboxsoftware.com/GBSpreadsheetFree.htm.


They have a free version with all features but limited to 150 rows per sheet and 5 sheets per workbook, if that falls within your needs.


I haven't had need to use it myself yet, but does look interesting.



If you're creating Excel 2007/2010 files give this open source project a try: http://closedxml.codeplex.com



The various Office 2003 XML libraries avaliable work pretty well for smaller excel files. However, I find the sheer size of a large workbook saved in the XML format to be a problem. For example, a workbook I work with that would be 40MB in the new (and admittedly more tightly packed) XLSX format becomes a 360MB XML file.


As far as my research has taken me, there are two commercial packages that allow output to the older binary file formats. They are:



Neither are cheap (500USD and 800USD respectively, I think). but both work independant of Excel itself.


What I would be curious about is the Excel output module for the likes of OpenOffice.org. I wonder if they can be ported from Java to .Net.



I agree about generating XML Spreadsheets, here's an example on how to do it for C# 3 (everyone just blogs about it in VB 9 :P) http://www.aaron-powell.com/linq-to-xml-to-excel



I've just recently used FlexCel.NET and found it to be an excellent library! I don't say that about too many software products. No point in giving the whole sales pitch here, you can read all the features on their website.


It is a commercial product, but you get the full source if you buy it. So I suppose you could compile it into your assembly if you really wanted to. Otherwise it's just one extra assembly to xcopy - no configuration or installation or anything like that.


I don't think you'll find any way to do this without third-party libraries as .NET framework, obviously, does not have built in support for it and OLE Automation is just a whole world of pain.



IKVM + POI


Or, you could use the Interop ...



Here's a way to do it with LINQ to XML, complete with sample code:


Quickly Import and Export Excel Data with LINQ to XML


It's a little complex, since you have to import namespaces and so forth, but it does let you avoid any external dependencies.


(Also, of course, it's VB .NET, not C#, but you can always isolate the VB .NET stuff in its own project to use XML Literals, and do everything else in C#.)



Just want to add another reference to a third party solution that directly addresses your issue: http://www.officewriter.com


(Disclaimer: I work for SoftArtisans, the company that makes OfficeWriter)



Well,


you can also use a third party library like Aspose.


This library has the benefit that it does not require Excel to be installed on your machine which would be ideal in your case.



The Java open source solution is Apache POI. Maybe there is a way to setup interop here, but I don't know enough about Java to answer that.


When I explored this problem I ended up using the Interop assemblies.



Have you ever tried sylk?


We used to generate excelsheets in classic asp as sylk and right now we're searching for an excelgenerater too.


The advantages for sylk are, you can format the cells.



Some useful Excel automation in C# , u can find from the following link.


http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm


bolton.



Some 3rd party component vendors like Infragistics or Syncfusion provide very good Excel export capabilities that do not require Microsoft Excel to be installed.


Since these vendors also provide advanced UI grid components, these components are particularly handy if you want the style and layout of an excel export to mimic the current state of a grid in the user interface of your application.


If your export is intended to be executed server side with emphasis on the data to be exported and with no link to the UI, then I would go for one of the free open source options (e.g. ExcelLibrary).


I have previously been involved with projects that attempted to use server side automation on the Microsoft Office suite. Based on this experience I would strongly recommend against that approach.



You can create nicely formatted Excel files using this library: http://officehelper.codeplex.com/documentation
See below sample:


using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME))
{
helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;
helper.CurrentSheetName = "Sheet1";
helper.CurrentPosition = new CellRef("C3");

//the template xlsx should contains the named range "header"; use the command "insert"/"name".
helper.InsertRange("header");

//the template xlsx should contains the named range "sample1";
//inside this range you should have cells with these values:
//<name> , <value> and <comment>, which will be replaced by the values from the getSample()
CellRangeTemplate sample1 = helper.CreateCellRangeTemplate("sample1", new List<string> {"name", "value", "comment"});
helper.InsertRange(sample1, getSample());

//you could use here other named ranges to insert new cells and call InsertRange as many times you want,
//it will be copied one after another;
//even you can change direction or the current cell/sheet before you insert

//typically you put all your "template ranges" (the names) on the same sheet and then you just delete it
helper.DeleteSheet("Sheet3");
}

where sample look like this:


private IEnumerable<List<object>> getSample()
{
var random = new Random();

for (int loop = 0; loop < 3000; loop++)
{
yield return new List<object> {"test", DateTime.Now.AddDays(random.NextDouble()*100 - 50), loop};
}
}


http://www.codeproject.com/KB/cs/Excel_and_C_.aspx <= why not just use the built in power of windows, just install office on the server, any application that you install can be automated.


So much easier just use the native methods.


If it installed you can use it, this is the most awesome and under used feature in windows it was Dubbed COM back in the good old days, and it saves you tons of time and pain.


Or even easier just use the ref lib MS supplies - http://csharp.net-informations.com/excel/csharp-create-excel.htm



Look at samples how to create Excel files.


There are examples in C# and VB.NET


It manages XSL XSLX and CSV Excel files.



http://www.devtriogroup.com/ExcelJetcell/Samples




public class GridViewExportUtil
{
public static void Export(string fileName, GridView gv)
{
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))
{
// Create a form to contain the grid
Table table = new Table();

// add the header row to the table
if (gv.HeaderRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}

// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
GridViewExportUtil.PrepareControlForExport(row);
table.Rows.Add(row);
}

// add the footer row to the table
if (gv.FooterRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}

// render the table into the htmlwriter
table.RenderControl(htw);

// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}

/// <summary>
/// Replace any of the contained controls with literals
/// </summary>
/// <param name="control"></param>
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}

if (current.HasControls())
{
GridViewExportUtil.PrepareControlForExport(current);
}
}
}
}

Hi this solution is to export your grid view to your excel file it might help you out



There is a free solution to export data to excel, word, pdf without automation. http://www.codeproject.com/KB/cs/Excel_PDF_Word_ExportWiz.aspx


0 commentaires:

Enregistrer un commentaire