Solved

Export to Excel - C#

Posted on 2010-08-19
4
361 Views
Last Modified: 2012-05-10
Hello all,
I need to create a button to export data from sql to excel.
It needs to call a procedure that selects data from a database my 2 questions are:
1- how to export to excel?
2- how to have the title of each column on excel

thanks,
Caliu
0
Comment
Question by:Romacali
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 18

Expert Comment

by:Anil Golamari
ID: 33478565
0
 
LVL 4

Accepted Solution

by:
yesthatbob earned 500 total points
ID: 33478839
Well, in my opinion, your best bet is to write your data to a CSV (comma separated value) file. Excel can open CSV files natively (you won't need to do an import). Your first row in the CSV file can contain your column names. See the code below for an example...
// This code assumes you have a DataSet named ds that contains your data

			// Open a file for writing the values
			StringBuilder rowData = new StringBuilder();
			TextWriter tw = new StreamWriter(@"C:\Test.csv", false, Encoding.UTF8);
			
			// Get all of the column names...
			foreach (DataColumn col in ds.Tables[0].Columns)
			{
				// ...and write them to the first row
				rowData.AppendFormat("{0},", col.ColumnName);
			}

			// Remove last comma
			if (rowData.ToString().EndsWith(","))
				rowData.Remove(rowData.Length - 1, 1);
			
			// Write header to file
			tw.WriteLine(rowData);
			rowData.Clear();

			// Get each data row...
			foreach (DataRow row in ds.Tables[0].Rows)
			{
				// ...and each field in the row...
				foreach (object field in row.ItemArray)
				{
					// ...and write them to a new row
					rowData.AppendFormat("{0},", field.ToString());
				}

				// Remove last comma
				if (rowData.ToString().EndsWith(","))
					rowData.Remove(rowData.Length - 1, 1);

				// Write data to file
				tw.WriteLine(rowData);
				rowData.Clear();
			}

			// Clean up
			tw.Flush();
			tw.Close();

Open in new window

0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 33482706
Here an working funktion
public static void exportToExcel( System.Windows.Forms.DataGridView dg, string filePath, string sheetName )
{
    string stmt = "";
    System.Data.OleDb.OleDbConnection connection = null;
    try { System.IO.File.Delete( filePath ); } catch ( Exception ) { }
    try {
        connection = ToolsDB.CreateOleDbConnectionToExcell( filePath );
        connection.Open();

        // Create the colum names
        string tableName = sheetName;
        stmt = "CREATE TABLE " + tableName + " (";
        foreach ( System.Windows.Forms.DataGridViewColumn column in dg.Columns ) {
            if ( column.Visible ) {
                stmt += column.HeaderText;

                switch ( column.ValueType.ToString() ) {
                    case "System.Int32":
                    case "System.Int16":
                    case "System.Int64":
                        stmt += " int,";
                        break;
                    case "System.Double":
                    case "System.Decimal":
                    case "System.Float":
                        stmt += " float,";
                        break;
                    case "System.DateTime":
                        stmt += " date,";
                        break;
                    default:
                        stmt += " char(255),";
                        break;
                }
            }
        }
        stmt = stmt.Substring( 0, stmt.Length - 1 );
        stmt += ")";
        System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand( stmt, connection );
        cmd.ExecuteNonQuery();

        // copy data
        foreach ( System.Windows.Forms.DataGridViewRow row in dg.Rows ) {
            string stmt1 = "INSERT INTO [" + tableName + "] (";
            string stmt2 = " VALUES (";
            foreach ( System.Windows.Forms.DataGridViewColumn column in dg.Columns ) {
                if ( column.Visible ) {

                    stmt1 += column.HeaderText + ",";

                    switch ( column.ValueType.ToString() ) {
                        case "System.Int32":
                        case "System.Int16":
                        case "System.Int64":
                            stmt2 += row.Cells[column.Name].Value.ToString() + ",";
                            break;
                        case "System.Double":
                        case "System.Decimal":
                        case "System.Float":
                            stmt2 += String.Format( "{0,2:f2}", row.Cells[column.Name].Value ).Replace( ",", "." ) + ",";
                            break;
                        case "System.DateTime":
                            stmt2 += "'" + ((DateTime)row.Cells[column.Name].Value).ToString( "dd/MM/yyyy" ) + "',";
                            break;
                        default:
                            string text = row.Cells[column.Name].Value.ToString();
                            if ( text.Length > 254 ) text = text.Substring( 0, 254 );
                            stmt2 += "'" + text + "',";
                            break;
                    }
                }
            }
            stmt1 = stmt1.Substring( 0, stmt1.Length - 1 );
            stmt2 = stmt2.Substring( 0, stmt2.Length - 1 );
            stmt1 += ")";
            stmt2 += ")";
            stmt = stmt1 + stmt2;
            cmd = new System.Data.OleDb.OleDbCommand( stmt, connection );
            cmd.ExecuteNonQuery();
        }

    } catch ( Exception ex ) {
    }
    connection.Close();
}

Open in new window

0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 33482710
you can adapt this function do DataSet if you want, to export the data it uses oledb
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question