SIGN UP MEMBER LOGIN:    
ARTICLE

Creating an Excel Spreadsheet Programmatically

Posted by G Gnana Arun Ganesh Articles | Office Development January 22, 2002
The Interoperability services make it very easy to work with COM Capable Applications such as Word and Excel. This article reveals using Excel from a managed application. Excel is the spreadsheet component of Microsoft Office 2000.
Reader Level:
Download Files:
 

Introduction:

The Interoperability services make it very easy to work with COM Capable Applications such as Word and Excel. This article reveals using Excel from a managed application. Excel is the spreadsheet component of Microsoft Office 2000. The majority of Excel programmatic functionality is exposed through Automation via the type library Excel9.olb. The intention of this article is to express that a managed application can interrelate with Excel as a COM server.

The first step is to create a reference in our project to Excel 9.0 Objects Library. By using Tlbimp tool we can generate Excel.dll.

TlbImp Excel9.olb Excel.dll

By adding Excel.dll to our program we can use the functionality of the Excel.

Now let us see in detail how to create an Excel Spreadsheet? & Set values to the cell using C#. The codes for Creating, make visible, add a new workbook and to set a value for cell in the Excel file is shown below.

  1. Creating new excel.application:

    Application exc = new Application();
    if (exc == null
    )
    {
    Console.WriteLine("ERROR: EXCEL couldn't be started");
    return
    0;
    }

  2. To make application visible:

    exc.set_Visible(0, true);

  3. To get the workbooks collection:

    Workbooks workbooks = exc.Workbooks;
    _Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet, 0);

  4. To get the worksheets collection:

    _Worksheet worksheet = (_Worksheet) sheets.get_Item(1);
    if (worksheet == null)
    {
    Console.WriteLine ("ERROR in worksheet == null");
    }

  5. To set the value for cell:

    Range range1 = worksheet.get_Range("C1", Missing.Value);
    if (range1 == null)
    {
    Console.WriteLine ("ERROR: range == null");
    }
    const int
    nCells = 1;
    Object[] args1 =
    new
    Object[1];
    args1[0] = nCells;
    range1.GetType().InvokeMember("Value", BindingFlags.SetProperty,
    null, range1, args1);

Example:

using System;
using System.Reflection;
// For Missing.Value and BindingFlags
using System.Runtime.InteropServices;
// For COMException
using
Excel;
class
AutoExcel
{
public static int
Main()
{
Application exc =
new
Application();
if (exc == null
)
{
Console.WriteLine("ERROR: EXCEL couldn't be started!");
return
0;
}
exc.set_Visible(0,
true
);
Workbooks workbooks = exc.Workbooks;
_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet, 0);
Sheets sheets = workbook.Worksheets;
_Worksheet worksheet = (_Worksheet) sheets.get_Item(1);
if (worksheet == null
)
{
Console.WriteLine ("ERROR: worksheet == null");
}
Range range1 = worksheet.get_Range("C1", Missing.Value);
if (range1 == null
)
{
Console.WriteLine ("ERROR: range == null");
}
const int
nCells = 1;
Object[] args1 =
new
Object[1];
args1[0] = nCells;
range1.GetType().InvokeMember("Value", BindingFlags.SetProperty,
null
,range1, args1);
return
100;
}
}

Now let us observe how to send a single dimension array to Excel:

It is similar to set the value for the cell. Only change is we use array as args2[0] = array2.

const int nCell = 5;
Range range2 = worksheet.get_Range("A1", "E1");
int[] array2 = new int
[nCell];
for (int
i=0; i < array2.GetLength(0); i++)
{
array2[i] = i+1;
}
Object[] args2 =
new
Object[1];
args2[0] = array2;
range2.GetType().InvokeMember("Value", BindingFlags.SetProperty,
null
, range2, args2);

OutPut:



Conclusion:

With the help of TlbImp.exe tool we can generate .NET assembly from Type library files and we can use that functionality of Type library file in C#.

Login to add your contents and source code to this article
share this article :
post comment
 

Using the following library you can create new xlsx files based on a sample xlsx file, by reusing parts of the latter: http://officehelper.codeplex.com/

Posted by sinoai aron Feb 20, 2012

I need convert text to excel

Posted by ali m Feb 07, 2011

If you're trying to make Excel files on the server (without installing Office) then give my API a try: http://ClosedXML.CodePlex.com


Right now it's fairly robust but I want to get more feedback to keep improving it.

Posted by MDeLeon Dec 05, 2010

Microsoft does not recommend using Office application in server-side scenarios. There are great 3rd party .Net excel component in the market that do the same job (or even better).
From a comparison testing I performed about a year ago Spire.XLS for .NET is the best from the following perspectives:
1. Read/Write of excel
2. Support of embedding images
3. Size of result Excel file is very small
4. Convenient API and very similar to Office's one
5. Multi-threaded and multi-process support.
http://www.e-iceblue.com/Introduce/excel-for-net-introduce.html

Posted by Bill Peter Jul 09, 2010

Hello,
I am doing a project that involves designing an application using c#(visual studio) where the user enters 9 values and when they click 'next', the 9 values get saved in an excel spreadsheet and go to the next row. I have the buttons and data entry spaces set but i need help with the codes that will write those values to excel and save them there.
This is my first time using c# or really programming at all so i will appreciate help with this.
Thank you much!
Oppy

Posted by Opeyemi Oyefeso Nov 26, 2009
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Nevron Gauge for SharePoint
Become a Sponsor