
[+1827] [45] mistrmark
[2008-09-29 22:30:28]
[ c# .net excel file-io ]
[ ]


The "...without installing Ms Office?" part of the question sounds very unprofessional. You can generate any type of file from a C# program (with an xls or xlsx file being one of them). It's not a requirement that there is a program on your computer that can read it (say, binary). - Mike
(17) @Mike The "without requiring Excel to be installed" piece has nothing to do with being professional. It's about dependencies. The original text of the question was worded as: "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.)" It's unfortunate the question was drastically simplified. - Tony
(3) Assuming you were trying to do something sans library or external code, I can't speak for xls file, but for xlsx files, why not start by taking an existing one, renaming it to a zip file and exploring the contents? A little bit of reverse engineering will tell you quite a bit. There are several different xml files and rels files in the various folders and subfolders. Try exploring that and see if it's something you can replicate or see if you can find documentation on the various xml namespaces/schemas. - Alexander Ryan Baggett
[+1025] [2010-04-08 21:36:03] Mike Webb [ACCEPTED]


ExcelLibrary [1]




You can also use EPPlus [2], which works only for Excel 2007/2010 format files (.xlsx files). There's also NPOI [3] which works with both.


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

Here are a couple links for quick reference:
ExcelLibrary [5] - GNU Lesser GPL [6]
EPPlus [7] - GNU Lesser General Public License (LGPL) [8]
NPOI [9] - Apache License [10]

Here some example code for ExcelLibrary:


//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;

OleDbConnection con = new OleDbConnection(dbConnectionString);

string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();

adptr.SelectCommand = cmd;

//Add the table to the data set

ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);



(237) ExcelLibrary has been superseded by the exceptional EPPlus - Jan updates it regularly. Have been using it and it is one of the finest open source projects we've worked with. - Mark A
(2) It should be noted that ExcelLibrary has a lot of performance issues when dealing with large datasets(larger than 5000 rows with lots of columns). Currently doing a heavy modification of the code base at work so we can use it in a project. - rossisdead
EPPlus seems far less buggy than ExcelLibrary, BUT it is GPL and therefore only a solution for open source projects. - Seth
EPPlus is actually still technically GPL because it is a derived work (i.e. the code base is still based off of ExcelLibrary, and since that is GPL so is EPPlus ... you can't make some changes to GPL code and slap a LGPL license on it). Does anyone know of a way to write to Excel using either commercial code or true LGPL (or similarly licensed code). - Beep beep
ExcelLibrary doesn't work anymore. If you want to write Excel 2003 files (.xls) this library is working great: CSharpJExcel Make sure to download the C# port. - Chris
(6) What about ClosedXML? I may prove to be useful in your projects. - Amadeus Sánchez
EPPlus was THE solution for me :) - MohammadHossein R
[+575] [2010-03-29 12:25:54] Jan Källman

If you are happy with the xlsx format, try my GitHub project, EPPlus [1]. It started with the source from ExcelPackage, but today it's a total rewrite. It supports ranges, cell styling, charts, shapes, pictures, named ranges, AutoFilter and a lot of other stuff.


(72) License is now LGPL, release notes here: - Simon D
(3) @Paul Chernoch: We populate large Excel sheets with interop very quickly. The secret is to do a bulk update. Create a object [,] block, populate that, then write that matrix to Excel at one time: excelWorksheet.get_Range(range).Value2 = block; - Marc Meketon
[+169] [2011-08-16 09:25:58] Pellared

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



(3) Important to note that the DLL for this is just over 5 MB and limited to Office 2007 formats. But certainly the easiest and fastest solution which works for me. - Josh Brown
(16) Just a heads up that v2.5 is out and can be downloaded here. - Snuffleupagus
(2) A great sample of Microsoft Open XML SDK - Open XML Writer can be found at… Or see Stack Overflow solution… - Greg
(1) Please note that Open XML SDK are now open source and hosted on github. Also you don't need to install the SDK, just fire-up nuget and DocumentFormat.OpenXml is all you need. It works with .net standard 1.3. - horeaper
[+167] [2009-06-20 20:48:26] Leniel Maccaferri

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 [1] (Beta) also supports XLSX.

Take a look at my blog posts:

Creating Excel spreadsheets .XLS and .XLSX in C# [2]

NPOI with Excel Table and dynamic Chart [3]


(6) A note on NPOI - Row and Column references are zero-based. Does work well for populating an existing template. - John M
[+105] [2008-09-29 22:41:09] Panos

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

Typical example:


EDIT - Some more links:


(4) Can someone confirm if this works when running in x64? I am pretty sure Jet only works if your app is compiled or running in 32-bit mode. - Lamar
(2) I've just tested this connection and it failed on a Windows Server 2008 R2 x64 RC, seems like one have to install the 2007 Office System Driver: Data Connectivity Components [… - Chris Richner
(9) One should be very careful if using this method. I've found it very flaky for data that isn't in a perfect format. - Kenny Mann
(1) Microsoft has upgraded Jet, try this link… - Justin
(1) At a previous job, we used Microsoft Access Database Engine 2010 Redistributable. It took the form of an OLEDB driver that allowed reading from and writing to Excel files, as well as Access format files. Note that this download does not require you to install the entire Office suite. Note also that it comes in both 32-bit and 64-bit flavors. It is very important that you match the 32-bit or 64-bit version to the architecture of the host process that will access the file(s). In our case, the host process was SSIS. - Stephen G Tuggy
[+80] [2009-01-24 18:33:17] Joe Erickson

The commercial solution, SpreadsheetGear for .NET [1] will do it.

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

Disclaimer: I own SpreadsheetGear LLC


(10) You have a great product but I think a lot of people here are expecting free solutions. That might explain the down votes. - md1337
[+65] [2009-06-01 15:45:06] Nate

A few options I have used:

If XLSX is a must: ExcelPackage [1] 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 [2] 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 [3], the .NET port of Apache POI [4]. NPOI 2.0 (Alpha) [5] also supports XLSX.


Definitely true. ExcelPackage/ExML is only a good option if you need the XLSX support. - Nate
[+61] [2008-09-29 22:37:59] Forgotten Semicolon


I realize that you may not be coding this in a web application, but here is an example [1] 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.


(3) This solution worked fine for me, just note you cannot use .xlsx extension - Jill
[+48] [2009-02-12 15:04:46] Petr Snobelt

You can use ExcelXmlWriter [1].

It works fine.


[+47] [2010-11-23 16:33:00] Manuel




var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Sample Sheet");

(1) @Druid the license is LGPL assuming you don't modify the source code to ClosedXML it is free to use - Chris Marisic
[+46] [2008-09-29 22:34:23] GEOCHET

You actually might want to check out the interop classes available in C# (e.g. Microsoft.Office.Interop.Excel. You say no OLE (which this isn't), but the interop classes are very easy to use. Check out the C# Documentation here [1] (Interop for Excel starts on page 1072 of the C# PDF).

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

Please be warned of Microsoft's stance [2] on this:



(6) But you have to make sure that you dispose of everything manually, otherwise you will leak memory - MagicKat
I haven't changed Interop for EPPlus yet (but already on the half way) so I don't really know how much better life is with it, but dealing with Interop I got so much pain in very surprising cases nearly every time I needed something more complex than just create .xls/.xlsx file with simple table inside. And mentioned above 'twice-check-to-dispose-everything-magic' is one of that everyday pain. But yeah, it works, and most of the time it's enough. - pkuderov
Warning the Microsoft.Office.Interops library has a dependency on Excel being installed. Thus does not answer the user's question - Programming with Mark
[+34] [2011-12-05 12:08:36] Mike Gledhill





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


(1) This seems a bit misleading, as you are asking for a donation to get all of the features. - UrbanEsc
[+26] [2008-09-30 01:16:40] Sam Warwick

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


[+23] [2008-09-29 22:48:00] ManiacZX

You may want to take a look at GemBox.Spreadsheet [1].




[+22] [2016-10-07 18:03:31] Davis Jebaraj

Syncfusion Essential XlsIO [1] can do this. It has no dependency on Microsoft office and also has specific support for different platforms.

Code sample:

//Creates a new instance for ExcelEngine.
ExcelEngine excelEngine = new ExcelEngine();
IWorkbook workbook = excelEngine.Excel.Workbooks.Open(fileName);
//To-Do some manipulation|
//To-Do some manipulation
//Set the version of the workbook.
workbook.Version = ExcelVersion.Excel2013;
//Save the workbook in file system as xlsx format

The whole suite of controls is available for free through the community license [6] program if you qualify (less than 1 million USD in revenue). Note: I work for Syncfusion.


[+17] [2008-11-24 08:22:41] biozinc






This one works on both .net and java,and is not expensive. SmartXLS - liya
[+17] [2009-11-10 05:05:23] Dimi Takis


you can also use a third party library like Aspose [1].



(9) Yes you can, if you don't mind paying a minimum license fee of $999. Try the MikesKnowledgeBase library... which is $999 cheaper than this !! - Mike Gledhill
[+17] [2015-12-02 13:30:28] Sachin Dhir


Check this out OpenXML: Alternative that helps avoid installing MS Excel on Server [1]


[+15] [2008-09-30 03:53:10] Aaron Powell


[+15] [2009-02-15 08:12:37] EMP

I've just recently used FlexCel.NET [1] 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.




[+15] [2015-07-23 07:55:17] Harsha.Vaswani

I have written a simple code to export dataset to excel without using excel object by using System.IO.StreamWriter.

Below is the code which will read all tables from dataset and write them to sheets one by one. I took help from this article [1].

public static void exportToExcel(DataSet source, string fileName)
        const string endExcelXML = "</Workbook>";
        const string startExcelXML = "<xml version>\r\n<Workbook " +
                 "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
                 " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
                 "xmlns:x=\"urn:schemas-    microsoft-com:office:" +
                 "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
                 "office:spreadsheet\">\r\n <Styles>\r\n " +
                 "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
                 "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
                 "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
                 "\r\n <Protection/>\r\n </Style>\r\n " +
                 "<Style ss:ID=\"BoldColumn\">\r\n <Font " +
                 "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
                 "<Style     ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
                 " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
                 "ss:ID=\"Decimal\">\r\n <NumberFormat " +
                 "ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
                 "<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
                 "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
                 "ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
                 "ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
                 "</Styles>\r\n ";
        System.IO.StreamWriter excelDoc = null;
        excelDoc = new System.IO.StreamWriter(fileName);

        int sheetCount = 1;
        foreach (DataTable table in source.Tables)
            int rowCount = 0;
            excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
            for (int x = 0; x < table.Columns.Count; x++)
                excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
            foreach (DataRow x in table.Rows)
                //if the number of rows is > 64000 create a new page to continue output
                if (rowCount == 64000)
                    rowCount = 0;
                    excelDoc.Write(" </Worksheet>");
                excelDoc.Write("<Row>"); //ID=" + rowCount + "
                for (int y = 0; y < table.Columns.Count; y++)
                    System.Type rowType;
                    rowType = x[y].GetType();
                    switch (rowType.ToString())
                        case "System.String":
                            string XMLstring = x[y].ToString();
                            XMLstring = XMLstring.Trim();
                            XMLstring = XMLstring.Replace("&", "&");
                            XMLstring = XMLstring.Replace(">", ">");
                            XMLstring = XMLstring.Replace("<", "<");
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                           "<Data ss:Type=\"String\">");
                        case "System.DateTime":
                            //Excel has a specific Date Format of YYYY-MM-DD followed by  
                            //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
                            //The Following Code puts the date stored in XMLDate 
                            //to the format above
                            DateTime XMLDate = (DateTime)x[y];
                            string XMLDatetoString = ""; //Excel Converted Date
                            XMLDatetoString = XMLDate.Year.ToString() +
                                 "-" +
                                 (XMLDate.Month < 10 ? "0" +
                                 XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
                                 "-" +
                                 (XMLDate.Day < 10 ? "0" +
                                 XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
                                 "T" +
                                 (XMLDate.Hour < 10 ? "0" +
                                 XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
                                 ":" +
                                 (XMLDate.Minute < 10 ? "0" +
                                 XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
                                 ":" +
                                 (XMLDate.Second < 10 ? "0" +
                                 XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
                            excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
                                         "<Data ss:Type=\"DateTime\">");
                        case "System.Boolean":
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
                                    "<Data ss:Type=\"Number\">");
                        case "System.Decimal":
                        case "System.Double":
                            excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
                        case "System.DBNull":
                            throw (new Exception(rowType.ToString() + " not handled."));
            excelDoc.Write(" </Worksheet>");


(1) Like the article says though, that's XML that Excel will read rather than actually being an XLS file, which means that it might only work in Excel and not other programs that read spreadsheets. But it's probably better than the equivalent HTML table answers here! - Rup
Supports xlsx ? OpenXML ? - Kiquenet
[+14] [2011-08-23 16:52:27] Eisbaer



[+13] [2008-09-29 22:39:50] MagicKat

IKVM [1] + POI [2]

Or, you could use the Interop ...


[+12] [2008-09-30 01:39:05] Ryan Lundy


Quickly Import and Export Excel Data with LINQ to XML [1]




[+12] [2010-12-03 19:53:12] user529824

You can create nicely formatted Excel files using this library:
See below sample:

    helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;
    helper.CurrentSheetName = "Sheet1";
    helper.CurrentPosition = new CellRef("C3");


    helper.InsertRange(sample1, getSample());

    //it will be copied one after another;


where sample look like this:

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


[+12] [2011-02-16 11:47:30] Simen S





[+12] [2011-04-28 10:40:05] Gaurav
public class GridViewExportUtil
    public static void Export(string fileName, GridView gv)
        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)

                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)

                //  add the footer row to the table
                if (gv.FooterRow != null)

                //  render the table into the htmlwriter

                //  render the htmlwriter into the response

    /// <summary>
    /// Replace any of the contained controls with literals
    /// </summary>
    private static void PrepareControlForExport(Control control)
            Control current = control.Controls[i];
            if (current is LinkButton)
            else if (current is ImageButton)
            else if (current is HyperLink)
            else if (current is DropDownList)
            else if (current is CheckBox)

            if (current.HasControls())


[+10] [2017-02-27 23:30:08] Taterhead


An overview of the process involved is:

  1. Install the Open XML SDK with the tool.


I have developed a simple WPF app on github [1] which will run on Windows for this purpose. There is a placeholder class called GeneratedClass where you can paste the generated code. If you go back one version of the file, it will generate an excel file like this:

enter image description here


[+8] [2009-11-10 05:02:18] user35711



[+8] [2011-04-12 07:04:36] Bonnie Cornell

Look at samples how to create Excel files.

There are examples in C# and VB.NET

It manages XSL XSLX and CSV Excel files. [1]


[+7] [2008-09-30 00:53:38] Nick

The Java open source solution is Apache POI [1]. 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.


[+7] [2008-11-04 20:15:11] Stefan Koelle

Have you ever tried sylk?


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

[+6] [2010-07-09 19:21:26] ScaleOvenStove

You can just write it out to XML using the Excel XML format and name it with .XLS extension and it will open with excel. You can control all the formatting (bold, widths, etc) in your XML file heading.

There is an example XML from Wikipedia [1].


[+5] [2009-10-22 15:21:25] community_owned

I also vote for GemBox.Spreadsheet [1].

Very fast and easy to use, with tons of examples on their site.

Took my reporting tasks on a whole new level of execution speed.


[+5] [2017-12-07 20:40:09] AlexDev

One really easy option which is often overlooked is to create a .rdlc report using Microsoft Reporting [1] and export it to excel format. You can design it in visual studio and generate the file using:

localReport.Render("EXCELOPENXML", null, ((name, ext, encoding, mimeType, willSeek) => stream = new FileStream(name, FileMode.CreateNew)), out warnings);

You can also export it do .doc or .pdf, using "WORDOPENXML" and "PDF" respectively, and it's supported on many different platforms such as ASP.NET and SSRS.

It's much easier to make changes in a visual designer where you can see the results, and trust me, once you start grouping data, formatting group headers, adding new sections, you don't want to mess with dozens of XML nodes.


[+4] [2010-11-22 10:42:03] Jens

Look for ExtremeML. It's a pretty cool library which enables you to use the OpenXML format for generating OpenXML files.

It's also an OpenSource project.

Link appears to be dead - Portland Runner
[+3] [2011-02-09 10:39:33] Craig Mc <= 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 -

Why is the second way easier? Isn't it the same (adding the native object library to your project)? Do you need to have Excel installed to get this object library working? - Slauma
(7) Microsoft does not recommend or support Office Automation from non-interactive applications such as ASP.NET. See - TrueWill
Excel is quite unreliable & slow when it comes to Automation. - Leslie Godwin
[+2] [2019-12-05 21:14:52] Michael Mainer

How to create an Excel (.xslx) file using C# on OneDrive without installing Microsoft Office

The Microsoft Graph API [1] provides File and Excel APIs for creating and modifying Excel files stored in OneDrive for both enterprise and consumer accounts. The Microsoft.Graph [2] NuGet package provides many interfaces for working with the File and Excel APIs.

  Name = "myExcelFile.xslx",
  File = new Microsoft.Graph.File()

// Create an empty file in the user's OneDrive.
var excelWorkbookDriveItem = await graphClient.Me.Drive.Root.Children.Request().AddAsync(excelWorkbook);

// Add the contents of a template Excel file.
DriveItem excelDriveItem;
using (Stream ms = ResourceHelper.GetResourceAsStream(ResourceHelper.ExcelTestResource))
    //Upload content to the file. ExcelTestResource is an empty template Excel file.
    excelDriveItem = await graphClient.Me.Drive.Items[excelWorkbookDriveItem.Id].Content.Request().PutAsync<DriveItem>(ms);

At this point, you now have an Excel file created in the user (enterprise or consumer) or group's OneDrive. You can now use the Excel APIs [3] to make changes to the Excel file without using Excel and without needing to understand the Excel XML format.


[+1] [2017-04-05 09:00:59] Gayan Chinthaka Dharmarathna

If you make data table or datagridview from the code you can save all data using this simple method.this method not recomended but its working 100%, even you are not install MS Excel in your computer.

  SaveFileDialog saveFileDialog1 = new SaveFileDialog();
  saveFileDialog1.Filter = "Excel Documents (*.xls)|*.xls";
  saveFileDialog1.FileName = "Employee Details.xls";
  if (saveFileDialog1.ShowDialog() == DialogResult.OK)
  string fname = saveFileDialog1.FileName;
  StreamWriter wr = new StreamWriter(fname);
  for (int i = 0; i <DataTable.Columns.Count; i++)
  wr.Write(DataTable.Columns[i].ToString().ToUpper() + "\t");

  //write rows to excel file
  for (int i = 0; i < (DataTable.Rows.Count); i++)
  for (int j = 0; j < DataTable.Columns.Count; j++)
  if (DataTable.Rows[i][j] != null)
  wr.Write(Convert.ToString(getallData.Rows[i][j]) + "\t");
   //go to next line
   //close file
   catch (Exception)
    MessageBox.Show("Error Create Excel Sheet!");

[+1] [2017-09-27 15:18:35] Vladimir Venegas

Some time ago, I created a DLL on top of NPOI. It's very simple to use it:

IList<DummyPerson> dummyPeople = new List<DummyPerson>();
//Add data to dummyPeople...
IExportEngine engine = new ExcelExportEngine();
MemoryStream memory = engine.Export();

You could read more about it on here [1].

By the way, is 100% open source. Feel free to use, edit and share ;)


[+1] [2018-11-05 07:46:39] Vijay Dodamani

To save xls into xlsx format, we just need to call SaveAs method from Microsoft.Office.Interop.Excel library. This method will take around 16 parameters and one of them is file format as well.

Microsoft document: Here SaveAs Method Arguments [1]

The object we need to pass is like

wb.SaveAs(filename, 51, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, false, false, 1,1, true, 
System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value)

Here, 51 is is enumeration value for XLSX

For SaveAs in different file formats you can refer the xlFileFormat [2]


[0] [2019-12-20 19:02:46] Roman.Pavelko

You can try my SwiftExcel [1] library. This library writes directly to the file, so it is very efficient. For example you can write 100k rows in few seconds without any memory usage.

Here is a simple example of usage:

using (var ew = new ExcelWriter("C:\\temp\\test.xlsx"))
    for (var row = 1; row <= 10; row++)
        for (var col = 1; col <= 5; col++)
            ew.Write($"row:{row}-col:{col}", col, row);

[-1] [2019-01-04 05:17:40] Shubham

check this out no need for third party libraries you can simply export datatable data to excel file using this

var dt = "your code for getting data into datatable";
            Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd")));
            Response.ContentType = "application/";
            string tab = "";
            foreach (DataColumn dataColumn in dt.Columns)
                Response.Write(tab + dataColumn.ColumnName);
                tab = "\t";
            int i;
            foreach (DataRow dataRow in dt.Rows)
                tab = "";
                for (i = 0; i < dt.Columns.Count; i++)
                    Response.Write(tab + dataRow[i].ToString());
                    tab = "\t";

(4) That generates a tab-separated file and saves it with an .XLS extension so that it gets opened by Excel. It's not a real Excel file, and you can't include formatting etc. There are similar answers here which try the same trick with HTML and the wrong extension. - Rup
[-1] [2019-12-03 07:42:47] Programming with Mark

All the current answers provide very specific solutions. I would like to provide you with a higher-level overview of your options.

When looking to creating Excel spreadsheets in C#, you have the following options:

  1. Use Microsoft's Office.Interops library
  2. Use a third-party library

For 1. Importantly, the Microsoft.Office.Interops library requires Excel to be installed. Additionally, since it interacts with Excel directly will exhibit crippling performance issues if you are working with large datasets or large amount of files.

For 2. There are a number of open-source third party libraries you can make use of. The other answers give you a sense of different libraries available.

As at end 2019, the following open-source libraries are most popular with developers (judged by Github stars):

Here is some sample code how you would create a spreadsheet using EPPlus:

   // file location
    var excelFileName = new FileInfo(@"C:\Temp\NewFile.xlsx");

    //lets create the file
    using (var excelFile = new ExcelPackage(excelFileName))
        // add a worksheet

[-7] [2014-12-20 06:37:43] saurabh27

I am using following code for create excel 2007 file which create the file and write in that file but when i open the file but it give me error that exel cannot open the file bcz file might be coruupted or extension of the file is not compatible. but if i used .xls for file it work fines

for (int i = 0; i < TotalFile; i++)
    if (innerloop == SplitSize)
        for (int j = 0; j < SplitSize; j++)
            string strContact = DSt.Tables[0].Rows[i * SplitSize + j][0].ToString();
        string strExcel = strFileName + "_" + i.ToString() + ".xlsx";
                         File.WriteAllLines(strExcel, Contact.ToArray());

also refer link

(2) That all relies on your Contact class, and you haven't told us what that is. If it works for xls then chances are you're actually writing out HTML which isn't a real Excel file. And your link is using interop, which as mentioned above shouldn't be used server-side and can be slow filling large tables. - Rup
(1) Contact is linkedlist not a class.declare a linkledist and used it because i haven't know the size of data so i used linkedlist. - saurabh27
(1) Oh, so you're producing a plain text file with one item per line? So Excel is treating it as a CSV without the commas? - Rup