How to Create an Excel (.Xls and .Xlsx) File in C# Without Installing Microsoft Office

How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

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's also NPOI which works with both.

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 (LGPL) - No longer maintained

EPPlus 5 - Polyform Noncommercial - Starting May 2020

NPOI - Apache License

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.

How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

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's also NPOI which works with both.

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 (LGPL) - No longer maintained

EPPlus 5 - Polyform Noncommercial - Starting May 2020

NPOI - Apache License

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.

Create Excel files from C# without office

Unless you have Excel installed on the Server/PC or use an external tool (which is possible without using Excel Interop, see Create Excel (.XLS and .XLSX) file from C#), it will fail. Using the interop requires Excel to be installed.

C# - convert xls file to xlsx without office components

Thanks to @Tim Schmelter.
Here is the code I got from the links:

private static string GetConnectionString()
{
Dictionary<string, string> props = new Dictionary<string, string>();

// XLSX - Excel 2007, 2010, 2012, 2013
props["Provider"] = "Microsoft.ACE.OLEDB.12.0;";
props["Extended Properties"] = "Excel 12.0 XML";
props["Data Source"] = @"D:\data\users\liran-fr\Desktop\Excel\Received\Orbotech_FW__ARTEMIS-CONTROL-AG__223227__0408141043__95546.xls";

// XLS - Excel 2003 and Older
//props["Provider"] = "Microsoft.Jet.OLEDB.4.0";
//props["Extended Properties"] = "Excel 8.0";
//props["Data Source"] = "C:\\MyExcel.xls";

StringBuilder sb = new StringBuilder();

foreach (KeyValuePair<string, string> prop in props)
{
sb.Append(prop.Key);
sb.Append('=');
sb.Append(prop.Value);
sb.Append(';');
}

return sb.ToString();
}

private static DataSet ReadExcelFile()
{
DataSet ds = new DataSet();

string connectionString = GetConnectionString();

using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;

// Get all Sheets in Excel File
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

// Loop through all Sheets to get data
foreach (DataRow dr in dtSheet.Rows)
{
string sheetName = dr["TABLE_NAME"].ToString();

//if (!sheetName.EndsWith("$"))
// continue;

// Get all rows from the Sheet
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";

DataTable dt = new DataTable();
dt.TableName = sheetName;

OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);

ds.Tables.Add(dt);
}

cmd = null;
conn.Close();
}

return ds;
}
using (ExcelPackage epackage = new ExcelPackage())
{
ExcelWorksheet excel = epackage.Workbook.Worksheets.Add("ExcelTabName");
DataSet ds = ReadExcelFile();
DataTable dtbl = ds.Tables[0];
excel.Cells["A1"].LoadFromDataTable(dtbl, true);
System.IO.FileInfo file = new System.IO.FileInfo(@"D:\data\users\liran-fr\Desktop\Excel\Received\test.xlsx");
epackage.SaveAs(file);
}

How can I programmatically create, read, write an excel without having office installed?

write your excel in HTML table format:

<html>
<body>
<table>
<tr>
<td style="background-color:#acc3ff">Cell1</td>
<td style="font-weight:bold">Cell2</td>
</tr>
</table>
</body>
</html>

and give your file an xls extension. Excel will convert it automatically

Read/write Excel file without installing anything

For starters, you may well have the driver already installed, but only for 32-bit programs, while your program is running under 64-bit (or vice versa, but that's less common).

You can force a specific environment in your .csproj file. To force 32-bit, use:

<PropertyGroup>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>

and to force 64-bit:

<PropertyGroup>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

If the driver has been installed in the other environment, your code should connect successfully.

NB. You can list the available providers for the current environment using code like the following:

using System.Data;
using System.Data.OleDb;
using System.Linq;
using static System.Console;

var oleEnum = new OleDbEnumerator();
var data =
oleEnum.GetElements()
.Rows
.Cast<DataRow>()
.Select(row => (
name: row["SOURCES_NAME"] as string,
descr: row["SOURCES_DESCRIPTION"] as string
))
.OrderBy(descr => descr);
foreach (var (name, descr) in data) {
WriteLine($"{name,-30}{descr}");
}

What if you don't have the Microsoft.ACE.OLEDB.12.0 provider in either environment? If you can convert your .xlsx file to an .xls file, you could use the Microsoft Jet 4.0 OLE DB Provider, which has been installed in every version of Windows since Windows 2000 (only available for 32-bit).

Set the PlatformTarget to x86 (32-bit) as above. Then, edit the connection string to use the older provider:

using System.Data.OleDb;

var fileName = @"C:\ExcelFile.xls";
// note the changes to Provider and the first value in Extended Properties
var connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;" +
$"Data Source={fileName};" +
"Extended Properties=\"Excel 8.0;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\"";

using var conn = new OleDbConnection(connectionString);
conn.Open();

Once you have an open OleDbConnection, you can read and write data using the standard ADO .NET command idioms for interacting with a data source:

using System.Data;
using System.Data.OleDb;

var ds = new DataSet();
using (var conn = new OleDbConnection(connectionString)) {
conn.Open();

// assuming the first worksheet is called Sheet1

using (var cmd = conn.CreateCommand()) {
cmd.CommandText = "UPDATE [Sheet1$] SET Field1 = \"AB\" WHERE Field2 = 2";
cmd.ExecuteNonQuery();
}

using (var cmd1 = conn.CreateCommand()) {
cmd1.CommandText = "SELECT * FROM [Sheet1$]";
var adapter = new OleDbDataAdapter(cmd);
adapter.Fill(ds);
}
};

NB. I found that in order to update data I needed to remove the IMEX=1 value from the connection string, per this answer.


If you must use an .xlsx file, and you only need to read data from the Excel file, you could use the ExcelDataReader NuGet package in your project.

Then, you could write code like the following:

using System.IO;
using ExcelDataReader;

// The following line is required on .NET Core / .NET 5+
// see https://github.com/ExcelDataReader/ExcelDataReader#important-note-on-net-core
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

DataSet ds = null;
using (var stream = File.Open(@"C:\ExcelFile.xlsx", FileMode.Open, FileAccess.Read)) {
using var reader = ExcelReaderFactory.CreateReader(stream);
ds = reader.AsDataSet();
}

Another alternative you might consider is to use the Office Open XML SDK, which supports both reading and writing. I think this is a good starting point -- it shows both how to read from a given cell, and how to write information back into a cell.

Creating a excel file with Microsoft.Office.Interop.Excel without Excel installed

This library works without office installed: http://epplus.codeplex.com/
I have used it a few times and it worked nicely for me.



Related Topics



Leave a reply



Submit