Click here to Skip to main content
6,630,289 members and growing! (21,582 online)
Email Password   helpLost your password?
Enterprise Systems » Office Development » Microsoft Excel     Intermediate License: The Code Project Open License (CPOL)

Generate Excel files without using Microsoft Excel

By Serhiy Perevoznyk

A C# class to create Excel files without requiring Microsoft Excel.
C#, .NET, Dev
Version:2 (See All)
Posted:3 Mar 2009
Views:22,383
Bookmarked:69 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
21 votes for this article.
Popularity: 5.57 Rating: 4.22 out of 5

1

2
1 vote, 4.8%
3
7 votes, 33.3%
4
13 votes, 61.9%
5

Introduction

Generating Excel files from web pages or other applications is a major subject in many articles. I'd like to present here a solution that does not require MS Excel to be installed on the target computer. This article shows how to create Microsoft Excel Binary Interchange File Format (BIFF) without using Microsoft Excel. BIFF is the native file format for Excel data, and can be viewed and modified in Microsoft Excel 97 or later.

Approaches and problems

The technique that is most frequently used to transfer data to an Excel workbooks is Automation. With Automation, you can call methods and properties that are specific to Excel tasks, but this solution has many drawbacks. Some of them are described in the Microsoft Knowledge Base. Additionally, you have to manage the lifetime of the temporary XLS files created on the server. Also, it is slow, because Excel runs in a separate process.

ExcelWriter class

The solution presented here is to write directly to a stream in Excel binary file format. For this purpose, I created very small C# class called ExcelWriter.

ExcelWriter class diagram
/// <summary>
/// Produces Excel file without using Excel
/// </summary>
public class ExcelWriter
{
    private Stream stream;
    private BinaryWriter writer;

    private ushort[] clBegin = { 0x0809, 8, 0, 0x10, 0, 0 };
    private ushort[] clEnd = { 0x0A, 00 };


    private void WriteUshortArray(ushort[] value)
    {
        for (int i = 0; i < value.Length; i++)
            writer.Write(value[i]);
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="ExcelWriter"/> class.
    /// </summary>
    /// <param name="stream">The stream.</param>
    public ExcelWriter(Stream stream)
    {
        this.stream = stream;
        writer = new BinaryWriter(stream);
    }

    /// <summary>
    /// Writes the text cell value.
    /// </summary>
    /// <param name="row">The row.</param>
    /// <param name="col">The col.</param>
    /// <param name="value">The string value.</param>
    public void WriteCell(int row, int col, string value)
    {
        ushort[] clData = { 0x0204, 0, 0, 0, 0, 0 };
        int iLen = value.Length;
        byte[] plainText = Encoding.ASCII.GetBytes(value);
        clData[1] = (ushort)(8 + iLen);
        clData[2] = (ushort)row;
        clData[3] = (ushort)col;
        clData[5] = (ushort)iLen;
        WriteUshortArray(clData);
        writer.Write(plainText);
    }

    /// <summary>
    /// Writes the integer cell value.
    /// </summary>
    /// <param name="row">The row number.</param>
    /// <param name="col">The column number.</param>
    /// <param name="value">The value.</param>
    public void WriteCell(int row, int col, int value)
    {
        ushort[] clData = { 0x027E, 10, 0, 0, 0 };
        clData[2] = (ushort)row;
        clData[3] = (ushort)col;
        WriteUshortArray(clData);
        int iValue = (value << 2) | 2;
        writer.Write(iValue);
    }

    /// <summary>
    /// Writes the double cell value.
    /// </summary>
    /// <param name="row">The row number.</param>
    /// <param name="col">The column number.</param>
    /// <param name="value">The value.</param>
    public void WriteCell(int row, int col, double value)
    {
        ushort[] clData = { 0x0203, 14, 0, 0, 0 };
        clData[2] = (ushort)row;
        clData[3] = (ushort)col;
        WriteUshortArray(clData);
        writer.Write(value);
    }

    /// <summary>
    /// Writes the empty cell.
    /// </summary>
    /// <param name="row">The row number.</param>
    /// <param name="col">The column number.</param>
    public void WriteCell(int row, int col)
    {
        ushort[] clData = { 0x0201, 6, 0, 0, 0x17 };
        clData[2] = (ushort)row;
        clData[3] = (ushort)col;
        WriteUshortArray(clData);
    }

    /// <summary>
    /// Must be called once for creating XLS file header
    /// </summary>
    public void BeginWrite()
    {
        WriteUshortArray(clBegin);
    }

    /// <summary>
    /// Ends the writing operation, but do not close the stream
    /// </summary>
    public void EndWrite()
    {
        WriteUshortArray(clEnd);
        writer.Flush();
    }
}

Using the code

The ExcelWriter sample is a console application that writes an XLS file to the name and location specified. The XLS file that is created is simply an empty spreadsheet. Then, you can start to write cell values by calling the WriteCell method with the row number, column number, and a cell value as parameters:

namespace XLSExportDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream stream = new FileStream("demo.xls", FileMode.OpenOrCreate);
            ExcelWriter writer = new ExcelWriter(stream);
            writer.BeginWrite();
            writer.WriteCell(0, 0, "ExcelWriter Demo");
            writer.WriteCell(1, 0, "int");
            writer.WriteCell(1, 1, 10);
            writer.WriteCell(2, 0, "double");
            writer.WriteCell(2, 1, 1.5);
            writer.WriteCell(3, 0, "empty");
            writer.WriteCell(3, 1);
            writer.EndWrite();
            stream.Close();
        }
    }
}

The picture below shows the final result of this sample:

The ExcelWriter class supports numeric and text values for the cells, and can be used for exporting data from the database to an XLS file, or for producing an XLS stream from a website on the fly.

I hope this article gives you a head start in working with Excel files from .NET and C#.

History

  • 03 March 2009 - Initial submission.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Serhiy Perevoznyk


Member

Occupation: Architect
Location: Belgium Belgium

Other popular Office Development articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 31 (Total in Forum: 31) (Refresh)FirstPrevNext
GeneralCell limitation to 255 chars Pinmembereddy mulyono19:12 28 Oct '09  
GeneralDutch characters break the document PinmemberD.Janjicek21:40 10 Aug '09  
GeneralRe: Dutch characters break the document PinmemberDanielLey4:06 9 Oct '09  
QuestionCan I modify an existing file ? Pinmembertrikeur0:25 10 Jun '09  
QuestionHow to write a Cell with Date format? Pinmemberapiacheredelchino11:40 3 Jun '09  
QuestionRe: How to write a Cell with Date format? Pinmemberedgar_v_reyes11:55 28 Aug '09  
AnswerRe: How to write a Cell with Date format? PinmemberFilipKrnjic6:56 29 Aug '09  
GeneralRe: How to write a Cell with Date format? Pinmemberedgar_v_reyes13:42 14 Sep '09  
GeneralRe: How to write a Cell with Date format? PinmemberSerhiy Perevoznyk22:56 29 Oct '09  
GeneralCreate Workbook/Worksheet Pinmemberyemo3:41 31 May '09  
GeneralRe: Create Workbook/Worksheet Pinmembersenthilraj.cro1:36 31 Jul '09  
GeneralRe: Create Workbook/Worksheet Pinmembergg42370:56 20 Nov '09  
QuestionHow can I use your class to make users download an Excel file without actually creating it in server's disk? PinmemberUyduruk Adres10:13 24 May '09  
AnswerRe: How can I use your class to make users download an Excel file without actually creating it in server's disk? PinmemberSerhiy Perevoznyk1:13 25 May '09  
Generalpassing long UTF8 string creates xls file which is not readable in Excel 2003 Pinmembermisodocasny1:12 13 May '09  
GeneralRe: passing long UTF8 string creates xls file which is not readable in Excel 2003 PinmemberSerhiy Perevoznyk1:21 25 May '09  
GeneralBIFF Format specifications? Pinmemberdeafie7:59 16 Mar '09  
GeneralRe: BIFF Format specifications? PinmemberSerhiy Perevoznyk10:34 17 Mar '09  
GeneralI love it, thanks a lot! :D PinmemberSaintKith22:45 9 Mar '09  
Questionwell try. Is it possible for us to format the file using this way? Pinmemberliu xianyong17:24 3 Mar '09  
AnswerRe: well try. Is it possible for us to format the file using this way? PinmemberSerhiy Perevoznyk23:36 3 Mar '09  
GeneralRe: well try. Is it possible for us to format the file using this way? Pinmemberhrgy8420:36 9 Mar '09  
GeneralRe: well try. Is it possible for us to format the file using this way? PinmemberSerhiy Perevoznyk2:21 13 Mar '09  
GeneralRe: well try. Is it possible for us to format the file using this way? Pinmemberedgar_v_reyes10:41 9 Nov '09  
GeneralRe: well try. Is it possible for us to format the file using this way? PinmemberSerhiy Perevoznyk10:43 9 Nov '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 3 Mar 2009
Editor: Smitha Vijayan
Copyright 2009 by Serhiy Perevoznyk
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project