Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Good day all. I still have the exact same problem. OK, I have a table that is filled with all sorts of data. Including email. This data consists of tickets that are submitted to our company about problems on site. My job now is to create spreadsheets according to the email in the database.

So I have created a separate table just to read in all the email addresses. With that statement that includes distinct but the problem now is to create a workbook for every email address in the database and to fill the spreadsheet with all data that is connected to the email that is selected.

I used a dataset to get the data from the database. And a MySQL adapter to fill the data with. Then I used a foreach statement to iterate through the data entries but I am still stuck.

Could any one assist me? Please?

Thank you in advance
Posted
Updated 7-Dec-10 23:42pm
v2
Comments
vivekse 8-Dec-10 5:41am    
Need some more description and code.

1 solution

OK, i will paste my entire code-----

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using MySql.Data.MySqlClient;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;

namespace WorkingWithSQL_EXCEL
{



    class Program
    {
        static string var1;
        static void Main(string[] args)
        {
           
            try
            {
                if (Directory.Exists("C:\\Mica_Report"))


                    Console.WriteLine("C:\\Mica_Report already exists");


                else
                    Directory.CreateDirectory("C:\\Mica_Report");


                Console.WriteLine("1. Create Mica_Report if directory if it does not exist");


            }

            catch (Exception e)
            {
                Console.WriteLine("Error " + e);
            }

//--------------------------------------------------------------------------------------------------------------------------------------//
            try
            {
                string MyConString = "Server=south-srv01;Database=jmds;Uid=root;Pwd=F1sh1ng;";
                MySqlConnection sqlConn = new MySqlConnection(MyConString);
                //String cmdText = "DROP PROCEDURE IF EXISTS `jmds`.`hesk_tickets`";
                MySqlCommand cmd = sqlConn.CreateCommand();
                cmd.CommandText = "DROP TABLE IF EXISTS `jmds`.`hesk_combined`";
                sqlConn.Open();
                MySqlDataReader reader = cmd.ExecuteReader();

                if (reader.Read())
                {
                    //table exists..hence drop it..
                    cmd.ExecuteNonQuery();


                }

                sqlConn.Close();
                reader.Close();
                Console.WriteLine("1. Checking if table exist, if it does. Then delete it");
            }
            catch (Exception e)
            {
                Console.WriteLine("Error " + e);
            }

            //--------------------------------------------------------------------------------------------------------------------------------------//



            try
            {
                string MyConString = "Server=south-srv01;Database=jmds;Uid=root;Pwd=F1sh1ng;";
                MySqlConnection sqlConn = new MySqlConnection(MyConString);
                MySqlCommand cmd = sqlConn.CreateCommand();
                cmd.CommandText = "CREATE TABLE  jmds.hesk_combined LIKE jmds.hesk_tickets";//
                sqlConn.Open();
                MySqlDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    //table exists..hence drop it..
                    cmd.ExecuteNonQuery();
                }
                sqlConn.Close();
                reader.Close();
                Console.WriteLine("2. Create hesk_combined table (Still empty)");
            }

            catch (Exception e)
            {
                Console.WriteLine("Error " + e);
            }

            // Put data into the new table

            //--------------------------------------------------------------------------------------------------------------------------------------//
            try
            {
                string MyConString = "Server=south-srv01;Database=jmds;Uid=root;Pwd=F1sh1ng;";
                MySqlConnection sqlConn = new MySqlConnection(MyConString);
                MySqlCommand cmd = sqlConn.CreateCommand();
                cmd.CommandText = "INSERT INTO jmds.hesk_combined SELECT * FROM jmds.hesk_tickets";
                sqlConn.Open();
                MySqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    //table exists..hence drop it..
                    cmd.ExecuteNonQuery();

                }
                sqlConn.Close();
                reader.Close();
                Console.WriteLine("3. Insert hesk_tickets data into new table");
            }

            catch (Exception e)
            {
                Console.WriteLine("Error " + e);
            }


            //--------------------------------------------------------------------------------------------------------------------------------------//

            try
            {
                string MyConString2 = "Server=south-srv01;Database=jmds;Uid=root;Pwd=F1sh1ng;";
                MySqlConnection sqlConn = new MySqlConnection(MyConString2);
                MySqlCommand cmd2 = sqlConn.CreateCommand();
                cmd2.CommandText = "UPDATE hesk_combined JOIN hesk_replies ON hesk_combined.id = hesk_replies.id SET hesk_combined.message = hesk_replies.message, hesk_combined.id =hesk_replies.id, hesk_combined.name =hesk_replies.name  ;";

                
                sqlConn.Open();
                MySqlDataReader reader2 = cmd2.ExecuteReader();
                while (reader2.Read())
                {
                    //table exists..hence drop it..
                    cmd2.BeginExecuteReader();

                }
                sqlConn.Close();
                reader2.Close();
                Console.WriteLine("4. Update hesk_combined table with hesk_replies table data");
            }

            catch (Exception e)
            {
                Console.WriteLine("Error " + e);
            }
            //--------------------------------------------------------------------------------------------------------------------------------------//
            //////////try
            //////////{
            //////////    DataSet ds = new DataSet("New_DataSet");
            //////////    DataTable dt = new DataTable("New_DataTable");

            //////////    ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
            //////////    dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

            //////////    string MyConString3 = "Server=south-srv01;Database=jmds;Uid=root;Pwd=F1sh1ng;";
            //////////    MySqlConnection sqlConn3 = new MySqlConnection(MyConString3);
            //////////    MySqlCommand command3 = sqlConn3.CreateCommand();

            //////////    command3.CommandText = "SELECT * FROM `jmds`.`hesk_combined` order by id";


            //////////    sqlConn3.Open();
            //////////    MySqlDataAdapter adptr = new MySqlDataAdapter();


            //////////    adptr.SelectCommand = command3;
            //////////    adptr.Fill(dt);


            //////////    sqlConn3.Close();


            //////////    //Add the table to the data set
            //////////    ds.Tables.Add(dt);

            //////////    Excel.Application oXL;
            //////////    Excel.Workbook oWB;
            //////////    Excel.Worksheet oSheet;
            //////////    Excel.Range oRange;


            //////////    // Start Excel and get Application object. 
            //////////    oXL = new Excel.Application();

            //////////    // Set some properties 
            //////////    //oXL.Visible = true;
            //////////    oXL.DisplayAlerts = false;

            //////////    // Get a new workbook. 
            //////////    oWB = oXL.Workbooks.Add(Missing.Value);

            //////////    // Get the active sheet 
            //////////    oSheet = (Excel.Worksheet)oWB.ActiveSheet;
            //////////    oSheet.Name = "Mica_Ticket_Submit";


            //////////    sqlConn3.Open();
            //////////    int rowCount = 1;


            //////////    foreach (DataRow dr in dt.Rows)
            //////////    {
            //////////        rowCount += 1;

            //////////        for (int i = 1; i < dt.Columns.Count + 1; i++)
            //////////        {

            //////////            // Add the header the first time through 
            //////////            if (rowCount == 2)
            //////////            {
            //////////                oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;

            //////////            }
            //////////            oSheet.Cells[rowCount, i] = dr[i - 1].ToString();

            //////////        }

            //////////    }
            //////////    sqlConn3.Close();

            //////////    // Resize the columns 
            //////////    oRange = oSheet.get_Range(oSheet.Cells[1, 1],
            //////////    oSheet.Cells[rowCount, dt.Columns.Count]);
            //////////    oRange.EntireColumn.AutoFit();
            //////////    oRange.WrapText = true;


            //////////    // Find a word and replace it
            //////////    oXL.Cells.Replace("<br />", "", Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, true, System.Type.Missing, false, false);
            //////////    oXL.Cells.Replace("", "", Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, true, System.Type.Missing, false, false);
            //////////    oXL.Cells.Replace("            //////////    oXL.Cells.Replace("> ", "", Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, true, System.Type.Missing, false, false);


            //////////    // Save the sheet and close 
            //////////    oSheet = null;
            //////////    oRange = null;

            //////////    oWB.SaveCopyAs(@"C:\Mica_Report\OverAllReport.xls");
            //////////    //oWB.SaveAs("ExerciseNew.xls", Excel.XlFileFormat.xlWorkbookNormal,
            //////////    //    Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            //////////    //    Excel.XlSaveAsAccessMode.xlExclusive,
            //////////    //    Missing.Value, Missing.Value, Missing.Value,
            //////////    //    Missing.Value, Missing.Value);
            //////////    oWB.Close(Missing.Value, Missing.Value, Missing.Value);
               
            //////////    oWB = null;
            //////////    oXL.Quit();



            //////////    // Clean up 
            //////////    // NOTE: When in release mode, this does the trick 
            //////////    GC.WaitForPendingFinalizers();
            //////////    GC.Collect();
            //////////    GC.WaitForPendingFinalizers();
            //////////    GC.Collect();

            //////////    sqlConn3.Close();
            //////////}
            //////////catch (Exception e)
            //////////{
            //////////    Console.WriteLine("Error " + e);
            //////////}
            //////////Console.WriteLine("5. Create EXCEL spreadsheet in documents folder .");
            
            //--------------------------------------------------------------------------------------------------------------------------------------//
            //--------------------------------------------------------------------------------------------------------------------------------------//
            //--------------------------------------------------------------------------------------------------------------------------------------//
            
            // NAREEN's REPORT

            try
            {
                DataSet ds = new DataSet("New_DataSet");
                DataTable dt = new DataTable("New_DataTable");

                ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
                dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

                string MyConString3 = "Server=south-srv01;Database=jmds;Uid=root;Pwd=F1sh1ng;";
                MySqlConnection sqlConn3 = new MySqlConnection(MyConString3);
                //MySqlCommand command3 = sqlConn3.CreateCommand();

                MySqlCommand command = new MySqlCommand("select * from jmds.hesk_combined where email = @email", sqlConn3);


                MySqlParameter param = new MySqlParameter();
                param.ParameterName = "@email";
                param.Value = (var1);
                command.Parameters.Add(param);

                sqlConn3.Open();
                MySqlDataAdapter adptr = new MySqlDataAdapter();


                adptr.SelectCommand = command;
                adptr.Fill(dt);


           


                //Add the table to the data set
                ds.Tables.Add(dt);

                Excel.Application oXL;
                Excel.Workbook oWB;
                Excel.Worksheet oSheet;
                Excel.Range oRange;


                // Start Excel and get Application object. 
                oXL = new Excel.Application();

                // Set some properties 
                //oXL.Visible = true;
                oXL.DisplayAlerts = false;

                // Get a new workbook. 
                oWB = oXL.Workbooks.Add(Missing.Value);

                // Get the active sheet 
                oSheet = (Excel.Worksheet)oWB.ActiveSheet;
                


                int rowCount = 1;


                foreach (DataRow dr in dt.Rows)
                {
                    rowCount += 1;

                    var1 = (string)dr["DBEmail"];
                    oSheet.Name = var1;



                    for (int i = 1; i < dt.Columns.Count + 1; i++)
                    {
                        oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
                        // Add the header the first time through 
                        if (rowCount == 2)
                        {
                            oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;

                        }
                        

                    }
                    
                }
               

                // Resize the columns 
                oRange = oSheet.get_Range(oSheet.Cells[1, 1],
                oSheet.Cells[rowCount, dt.Columns.Count]);
                oRange.EntireColumn.AutoFit();
                oRange.WrapText = true;


                // Find a word and replace it
                oXL.Cells.Replace("<br />", "", Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, true, System.Type.Missing, false, false);
                oXL.Cells.Replace("", "", Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, true, System.Type.Missing, false, false);
                oXL.Cells.Replace("                oXL.Cells.Replace("", "", Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, true, System.Type.Missing, false, false);

                oWB.SaveCopyAs(@"C:\Mica_Report\new.xls");
                // Save the sheet and close 
                oSheet = null;
                oRange = null;

              
                //oWB.SaveAs("NareenReport.xls", Excel.XlFileFormat.xlWorkbookNormal,
                //    Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                //    Excel.XlSaveAsAccessMode.xlExclusive,
                //    Missing.Value, Missing.Value, Missing.Value,
                //    Missing.Value, Missing.Value);
                //oWB.Close(Missing.Value, Missing.Value, Missing.Value);

                oWB = null;
                oXL.Quit();



                // Clean up 
                // NOTE: When in release mode, this does the trick 
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();

               
            }
            catch (Exception e)
            {
                Console.WriteLine("Error " + e);

            }
            Console.WriteLine("Reports done in Process");
        }

    }
}
 
Share this answer
 
v2
Comments
fjdiewornncalwe 8-Dec-10 10:02am    
Please don't post the code as an answer. People will think that someone has already provided a resolution for your issue. Just use the "Improve Question" link and post the code as part of the question and wrap the code in the "pre" tag.

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900