Click here to Skip to main content
Licence CPOL
First Posted 29 Jan 2011
Views 164,332
Downloads 12,906
Bookmarked 296 times

Export Data to Excel, Word, PDF without Automation from DataBase

By | 8 Feb 2012 | Article
This article introduces how to export data from database to Excel, PDF, MS Word, HTML, MS clipboard ,XML, DBF, SQL Script, SYLK, DIF, CSV without Automation and Acrobat Reader.
 
Part of The SQL Zone sponsored by
See Also

Introduction

DataExportWizard, specially designed for developers/programmers, is used for exporting data from database such as Datatable, listview to Excel, PDF, MS Word, HTML, MS clipboard, XML, DBF, SQL Script, SYLK, DIF, CSV without Automation. This article focuses on introducing how to use this Wizard with source code.

This Wizard is developed based on a Free Data Export Component.

The following will be presented in article.

  1. Use GetFactoryClasses() method to get all factories
  2. How to make a connection with database
  3. How to get data source from database
  4. How to export data source from database
  5. How to export data to different formats(Word, Excel, PDF...)

This also can be Viewed as Video on YouTube

Background

This data export wizard was designed for different databases users who can easily export data to MS Office files or some other frequently used format files, for example, TXT and PDF. The following steps shows how to use this wizard and details about how to create this wizard.

Steps:

  1. Select a database.(SQL Client, OLE DB)
  2. Select data source from the database.(Table, View and SQL Command)
  3. Select columns as you want to export.
  4. Specify a file format to show the result and save it to a file with the specified format.( XLS, PDF, MS Word, HTML, MS clipboard ,XML, DBF, SQL Script, SYLK, DIF, CSV)

The step details are shown as following:

Step 1: Select a database

Choose Database which stored your data. The frequently used databases include SQL Client, OLE DB and so on. Then, Give the database connection string.

Load a local database:

It returns a datatable which contains the information of all DB providers on your PC by using GetFactoryClasses() method. You may read the DB provider by the name of the it. It displays on the drop-down list with its name. The "Next" button will not be activated until it connects the database you choose.

private void ChooseDatabase_Load(object sender, System.EventArgs e)
{
    //init db provider factories list
    this.cmbDbProvider.DataSource = DbProviderFactories.GetFactoryClasses();
    this.cmbDbProvider.DisplayMember = "Name";
    this.nextCommonButton.Enabled = false;
}

Step 2: Select data source from the database

Get the data source in the Database. It may be a table, a view or SQL Command. In this example, I choose Table.

Data source from table:

Data source from SQL Command:

Three types of data source in the database.When you choose "Table" and "View" types, the data source list can be visible. You can see all the tables which are stored in the database. If you choose "SQL Command", the SQL command is visible.

private void FillDataSourceList()
{
    String type = SelectedDataSourceType;
    this.gbDataSource.Text = type;
    
    DataExportWizardContext context = this.WizardContainer.Context as DataExportWizardContext;
    DbProviderFactory factory = DbProviderFactories.GetFactory(context.DbProviderFactoryName);
    using (DbConnection conn = factory.CreateConnection())
    {
        conn.ConnectionString = context.DbConnectionString;
        conn.Open();
        
        DataTable schema = null;
        switch (type)
        {
            case "Table":
                schema = conn.GetSchema("Tables");
                this.dgwDataSourceList.DataSource = schema;
                this.dgwDataSourceList.Visible = true;
                this.txtSQLCommand.Visible = false;
                break;

            case "View":
                schema = conn.GetSchema("Views");
                this.dgwDataSourceList.DataSource = schema;
                this.dgwDataSourceList.Visible = true;
                this.txtSQLCommand.Visible = false;
                break;

            case "SQLCommand":
                this.dgwDataSourceList.Visible = false;
                this.txtSQLCommand.Visible = true;
                break;
        }
    }
}

Step 3: Select columns

After selecting a Table, View or SQL Command, it will display all columns of it. If you don’t need all of the data in it, you may select columns of it. Just choose some of them you need.

What you select in the table will be stored in the value "schema". In other words, the schema is the data source.

private void LoadColumns()
{
    DataExportWizardContext context = this.WizardContainer.Context as DataExportWizardContext;
    DbProviderFactory factory = DbProviderFactories.GetFactory(context.DbProviderFactoryName);
    using (DbConnection conn = factory.CreateConnection())
    {
        conn.ConnectionString = context.DbConnectionString;
        conn.Open();
        
        DbCommand command = factory.CreateCommand();
        command.Connection = conn;
        if (context.TableName != null)
        {
          command.CommandText = String.Format(" SELECT * FROM {0} ", context.TableName);
        }
        else
        {
          command.CommandText = context.SQLCommand;
        }

        DataTable schema = null;
        try
        {
          DbDataReader result = command.ExecuteReader();
          schema = result.GetSchemaTable();
        }
        catch (Exception e)
        {
          String message = String.Format("Could not to acquire schema of data source.[{0}]", e.Message);
          MessageBox.Show(message, "DataExport Wizard", MessageBoxButtons.OK, MessageBoxIcon.Error);
          return;
        }
        schema.Columns.Add("ColumnSelected");
        foreach (DataRow row in schema.Rows)
        {
            row["ColumnSelected"] = true;
        }
        this.dgvColumns.AutoGenerateColumns = false;
        this.dgvColumns.DataSource = schema;
    }
}

Step 4: Specify a file format and Save

The last step is to show your data result with a specified file format. In the component, many formats are supported, such as XLS, PDF, MS Word, HTML, MS clipboard, XML and so on. And you may give a path to save the file.

Here, I give you the source code for two formats: XLS and RTF

In each format, the export result is decided by three parameters: The SQL command, the columns you choose in step three and the file name. Also you can set the style of each format.

XLS:

private void ExportData_XLS(DbCommand command, Spire.DataExport.Collections.StringListCollection columns, String fileName)
{
    Spire.DataExport.XLS.CellExport cellExport = new Spire.DataExport.XLS.CellExport();
    cellExport.ActionAfterExport = Spire.DataExport.Common.ActionType.OpenView;
    cellExport.AutoFitColWidth = true;
    cellExport.DataFormats.CultureName = "en-US";
    cellExport.DataFormats.Currency = "#,###,##0.00";
    cellExport.DataFormats.DateTime = "yyyy-M-d H:mm";
    cellExport.DataFormats.Float = "#,###,##0.00";
    cellExport.DataFormats.Integer = "#,###,##0";
    cellExport.DataFormats.Time = "H:mm";
    cellExport.SheetOptions.AggregateFormat.Font.Name = "Arial";
    cellExport.SheetOptions.CustomDataFormat.Font.Name = "Arial";
    cellExport.SheetOptions.DefaultFont.Name = "Arial";
    cellExport.SheetOptions.FooterFormat.Font.Name = "Arial";
    cellExport.SheetOptions.HeaderFormat.Font.Name = "Arial";
    cellExport.SheetOptions.HyperlinkFormat.Font.Color = Spire.DataExport.XLS.CellColor.Blue;
    cellExport.SheetOptions.HyperlinkFormat.Font.Name = "Arial";
    cellExport.SheetOptions.HyperlinkFormat.Font.Underline = Spire.DataExport.XLS.XlsFontUnderline.Single;
    cellExport.SheetOptions.NoteFormat.Alignment.Horizontal = Spire.DataExport.XLS.HorizontalAlignment.Left;
    cellExport.SheetOptions.NoteFormat.Alignment.Vertical = Spire.DataExport.XLS.VerticalAlignment.Top;
    cellExport.SheetOptions.NoteFormat.Font.Bold = true;
    cellExport.SheetOptions.NoteFormat.Font.Name = "Tahoma";
    cellExport.SheetOptions.NoteFormat.Font.Size = 8F;
    cellExport.SheetOptions.TitlesFormat.Font.Bold = true;
    cellExport.SheetOptions.TitlesFormat.Font.Name = "Arial";
    cellExport.Columns = columns;
    cellExport.SQLCommand = command;
    
    cellExport.FileName = fileName;
    cellExport.SaveToFile();
}

RTF:

private void ExportData_RTF(DbCommand command, Spire.DataExport.Collections.StringListCollection columns, String fileName)
{
  Spire.DataExport.RTF.RTFExport rtfExport = new Spire.DataExport.RTF.RTFExport();
  rtfExport.ActionAfterExport = Spire.DataExport.Common.ActionType.OpenView;
  rtfExport.DataFormats.CultureName = "en-US";
  rtfExport.DataFormats.Currency = "#,###,##0.00";
  rtfExport.DataFormats.DateTime = "yyyy-M-d H:mm";
  rtfExport.DataFormats.Float = "#,###,##0.00";
  rtfExport.DataFormats.Integer = "#,###,##0";
  rtfExport.DataFormats.Time = "H:mm";
  rtfExport.RTFOptions.DataStyle.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
  rtfExport.RTFOptions.FooterStyle.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
  rtfExport.RTFOptions.HeaderStyle.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
  rtfExport.RTFOptions.TitleStyle.Alignment = Spire.DataExport.RTF.RtfTextAlignment.Center;
  rtfExport.RTFOptions.TitleStyle.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Bold);

  rtfExport.Columns = columns;
  rtfExport.SQLCommand = command;

  rtfExport.FileName = fileName;
  rtfExport.SaveToFile();
}

Use the Component

Parameter Value
Database Choose one or add one unlisted
Data source Table, View or SQL Command
Columns Select columns to export
Export format Possible values:
XLS, PDF, MS Word, HTML, MS clipboard, XML and so on
Save path Select a local path

The Result

I made a result by selecting the format of XLS:

092e61d4.PNG

Supported Database

If we have a database-provider, DataExportWizard could support any database. Editing the App.config file can add other database providers. All installed providers that implement System.Data.Common.DbProviderFactory will be automatically filled in the Database-Provider list of the first step.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.data>
    <DbProviderFactories>
      <add name="SqlClient Data Provider"
       invariant="System.Data.SqlClient"
       description=".Net Framework Data Provider for SqlServer"
       type="System.Data.SqlClient.SqlClientFactory, System.Data, 
     Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
      <add name="OLE DB Data Provider"
       invariant="System.Data.OleDb"
       description=".Net Framework Data Provider for OLE DB"
       type="System.Data.OleDb.OleDbFactory, System.Data, 
     Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
    </DbProviderFactories>
  </system.data>
</configuration>

Conclusion

This article fouces on how to export data to different kinds of format files. And I shows the data source on how to develop DataExport Wizard. The design of this Wizard originates from one free data export component. If you think that the component will be helpful for you, you can download it from here.

License

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

About the Author

rlejason

Program Manager

United States United States

Member

I'm a software engineer living in New York. And my hobby is to read data from database, and then represent them in a local file.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 1 Pinmembermail-2223:51 15 Apr '12  
GeneralMy vote of 4 Pinmemberchandru201121:50 20 Feb '12  
GeneralMy vote of 5 Pinmembermanoj kumar choubey0:31 10 Feb '12  
GeneralMy vote of 5 Pinmembertdngan21:13 8 Feb '12  
GeneralMy vote of 5 PinmemberMember 839296318:31 8 Jan '12  
GeneralMy Vote of 5 PinmemberRaviRanjankr4:52 31 Dec '11  
QuestionHow to save a scanned text Pinmembermayur csharp G19:45 7 Nov '11  
AnswerRe: How to save a scanned text Pinmemberrlejason19:15 5 Dec '11  
AnswerRe: How to save a scanned text PinmemberJamesHoward97222:26 20 Dec '11  
GeneralMy vote of 4 PinmemberSAGKAN18:55 9 Oct '11  
GeneralRe: My vote of 4 Pinmemberrlejason19:12 5 Dec '11  
GeneralMy vote of 4 PinmemberRyan Giggs15:04 27 Sep '11  
GeneralRe: My vote of 4 Pinmemberrlejason19:12 5 Dec '11  
GeneralMy vote of 2 Pinmembersujit07610:44 27 Sep '11  
GeneralRe: My vote of 2 Pinmemberrlejason19:11 5 Dec '11  
GeneralMy vote of 3 PinmemberVivek Krishnamurthy21:07 28 Jun '11  
GeneralRe: My vote of 3 Pinmemberrlejason23:48 31 Jul '11  
GeneralMy vote of 5 Pinmemberdeloteric20:52 6 Jun '11  
GeneralRe: My vote of 5 Pinmemberrlejason22:13 7 Jun '11  
GeneralMy vote of 5 PinmemberFilip D'haene6:43 24 May '11  
GeneralRe: My vote of 5 Pinmemberrlejason22:18 24 May '11  
GeneralMy vote of 5 PingroupOtherControls2:10 6 May '11  
GeneralRe: My vote of 5 Pinmemberrlejason22:14 9 May '11  
GeneralMy vote of 3 PinmemberOshtri Deka22:03 2 May '11  
GeneralRe: My vote of 3 Pinmemberrlejason22:14 9 May '11  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 9 Feb 2012
Article Copyright 2011 by rlejason
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid