Click here to Skip to main content
Click here to Skip to main content

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

By , 8 Feb 2012
 

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

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionMultiple Sheetmemberalc_gombloh15-Nov-12 15:52 
GeneralMy vote of 3memberashutoshmishra17124-Jun-12 5:13 
GeneralMy vote of 1membermail-2215-Apr-12 23:51 
GeneralMy vote of 4memberchandru201120-Feb-12 21:50 
GeneralMy vote of 5membermanoj kumar choubey10-Feb-12 0:31 
GeneralMy vote of 5membertdngan8-Feb-12 21:13 
GeneralMy vote of 5memberMember 83929638-Jan-12 18:31 
GeneralMy Vote of 5memberRaviRanjankr31-Dec-11 4:52 
QuestionHow to save a scanned textmembermayur csharp G7-Nov-11 19:45 
AnswerRe: How to save a scanned textmemberrlejason5-Dec-11 19:15 
AnswerRe: How to save a scanned textmemberJamesHoward97220-Dec-11 22:26 
GeneralMy vote of 4memberSAGKAN9-Oct-11 18:55 
GeneralRe: My vote of 4memberrlejason5-Dec-11 19:12 
GeneralMy vote of 4memberRyan Giggs27-Sep-11 15:04 
GeneralRe: My vote of 4memberrlejason5-Dec-11 19:12 
GeneralMy vote of 2membersujit076127-Sep-11 0:44 
GeneralRe: My vote of 2memberrlejason5-Dec-11 19:11 
GeneralMy vote of 3memberVivek Krishnamurthy28-Jun-11 21:07 
GeneralRe: My vote of 3memberrlejason31-Jul-11 23:48 
GeneralMy vote of 5memberdeloteric6-Jun-11 20:52 
GeneralRe: My vote of 5memberrlejason7-Jun-11 22:13 
GeneralMy vote of 5memberFilip D'haene24-May-11 6:43 
GeneralRe: My vote of 5memberrlejason24-May-11 22:18 
GeneralMy vote of 5groupOtherControls6-May-11 2:10 
GeneralRe: My vote of 5memberrlejason9-May-11 22:14 
GeneralMy vote of 3memberOshtri Deka2-May-11 22:03 
GeneralRe: My vote of 3memberrlejason9-May-11 22:14 
GeneralMy vote of 2memberambarishtv27-Apr-11 0:32 
GeneralRe: My vote of 2memberrlejason9-May-11 22:14 
GeneralMy vote of 2memberJV999912-Apr-11 1:15 
GeneralRe: My vote of 2memberrlejason9-May-11 22:13 
GeneralMy vote of 5memberhoukai0710-Apr-11 5:34 
GeneralRe: My vote of 5memberrlejason11-Apr-11 22:20 
GeneralMy vote of 5memberRidho Anggoro4-Apr-11 23:15 
GeneralRe: My vote of 5memberrlejason7-Apr-11 18:00 
GeneralTrying to reimplement the wizardmemberCikaPero4-Apr-11 23:08 
QuestionHUH ??memberdburr4-Apr-11 12:28 
AnswerRe: HUH ??memberrlejason7-Apr-11 18:00 
GeneralRe: HUH ??memberdburr7-Apr-11 20:00 
GeneralRe: HUH ??memberOshtri Deka2-May-11 22:01 
GeneralRe: HUH ??memberNitesh Luharuka15-Sep-11 17:51 
GeneralHi, I give you 5 Point but one is missingmemberEDVBS26-Mar-11 23:19 
GeneralRe: Hi, I give you 5 Point but one is missingmemberrlejason28-Mar-11 15:21 
GeneralRe: Hi, I give you 5 Point but one is missingmemberEDVBS28-Mar-11 19:33 
GeneralRe: Hi, I give you 5 Point but one is missingmemberJohnPool30-Mar-11 3:48 
GeneralRe: Hi, I give you 5 Point but one is missingmemberEDVBS30-Mar-11 5:23 
GeneralRe: Hi, I give you 5 Point but one is missingmemberrlejason30-Mar-11 16:53 
QuestionHas anyone been able to successfully register with Ice Blue?memberDoncp22-Mar-11 10:42 
AnswerRe: Has anyone been able to successfully register with Ice Blue?memberrlejason22-Mar-11 23:34 
GeneralRealy FantasticmemberPatil Yogesh22-Mar-11 0:52 

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

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