Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i have the following codes which allow me to export the data in datatable into excel file. But every time i run the program, the data would not be saved. Or more precise, it didnt run some part of the code at all. Below are my codes:

C#
public static class DataTable_Extensions
    {
        public static void ExportToExcel(this DataTable dt, string folderPath) 
        {
            try 
            {
                if (dt == null || dt.Columns.Count == 0) 
                {
                    throw new Exception("ExportToExcel: Null or empty input table!\n");
                }

                //load the excel and create a new one
                Excel.Application excelApp = new Excel.Application();
                excelApp.Workbooks.Add();

                //one worksheet
                Excel._Worksheet workSheet = excelApp.ActiveSheet;

                //heading for the columns
                for (int i = 0; i < dt.Columns.Count; i++) 
                {
                    workSheet.Cells[1, (i + 1)] = dt.Columns[i].ColumnName;
                }
                //rows
                for (int i = 0; i < dt.Rows.Count; i++) 
                {
                    for (int j = 0; j < dt.Columns.Count; j++) 
                    { 
                        workSheet.Cells[(i+2), (j+1)] = dt.Rows[i][j];
                    }
                }

                //filepath
                //part that it didnt enter
                if (folderPath != null && folderPath != "") 
                {
                    try
                    {
                        workSheet.SaveAs(folderPath);
                        excelApp.Quit();
                        Console.Write("Excel file saved!");
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("ExportToExcel: Excel file could not be saved! Please check file path again." + ex.Message);
                    }
                }
                else 
                {
                    excelApp.Visible = true;
                }
            }
            catch (Exception ex) 
            {
                throw new Exception("ExportToExcel: \n" + ex.Message);
            }
        }       
Posted
Comments
Bhushan Patki 5-Jun-14 3:45am    
where exactly the code break?
Jamie888 5-Jun-14 3:52am    
if (folderPath != null && folderPath != "") at here
DamithSL 5-Jun-14 4:06am    
how you call this method?
Jamie888 5-Jun-14 4:56am    
from another function like : dt.ExportToExcel(TargetFolder);
DamithSL 5-Jun-14 4:59am    
check my answer

Save excelApp also
excelApp .SaveAs(folderPath);
 
Share this answer
 
Comments
Jamie888 5-Jun-14 3:25am    
excepApp didnt have an extension for SaveAs.
in case of no folderpath provider you need to set folder path like below. add below code at the beginning of your method
C#
if (string.IsNullOrEmpty(folderPath))
{
  folderPath= Path.Combine( Environment.CurrentDirectory ,DateTime.Now.ToString("yyyyMMddHHmmssfff")+".xlsx");
}
 
Share this answer
 
v2
C#
class Program
    {
        public static bool DebugMode { get; set; }
        public static string TargetFolder { get; set; }
        public static DateTime StartDate { get; set; }
        public static DateTime EndDate { get; set; }
        public static string DebugFolder { get; set; }
        static void Main(string[] args)
        {
            //new Gemini();
            Program p = new Program();

            DebugMode = Convert.ToBoolean(ConfigurationManager.AppSettings["DebugMode"]);
            TargetFolder = Convert.ToString(ConfigurationManager.AppSettings["TargetFolder"]);
            DebugFolder = Convert.ToString(ConfigurationManager.AppSettings["DebugFolder"]);
            StartDate = Convert.ToDateTime(ConfigurationManager.AppSettings["StartDate"]);
            EndDate = Convert.ToDateTime(ConfigurationManager.AppSettings["EndDate"]);

            if (DebugMode)
            {
                var GeminiConnString = ConfigurationManager.ConnectionStrings["GeminiConnString"].ConnectionString;
                SqlConnection conn = null;
                SqlCommand command = null;
                DataTable dt = new DataTable();
                DataSet ds = new DataSet();

                using (conn = new SqlConnection(GeminiConnString)) 
                {
                    using (command = new SqlCommand("dbo.GetGeminiRecordByDate", conn))
                    {
                        conn.Open();
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.AddWithValue("@startDate", StartDate);
                        command.Parameters.AddWithValue("@endDate", EndDate);
                        
                        command.ExecuteNonQuery();

                        SqlDataAdapter da = new SqlDataAdapter(command);
                        da.Fill(ds);
                        dt = ds.Tables[0];

                        //Console.Write("Issue ID");

                        foreach (DataRow dRow in dt.Rows)
                        {
                            Console.WriteLine();
                            Console.Write(dRow["issueid"].ToString());
                            Console.Write('\t');
                            Console.Write(dRow["typedesc"].ToString());
                        }                      
                    } 
                }
                p.ExportToExcel(ds, TargetFolder);
            }
            
        }
        private void ExportToExcel(DataSet ds, string folderPath)
        {
            try
            {
                //load the excel and create a new one
                Excel.Application excelApp = new Excel.Application();

                //open a predefine excel file
                Excel.Workbook excelWorkBook = excelApp.Workbooks.Add();

                foreach (DataTable dt in ds.Tables)
                {
                    //one worksheet
                    Excel.Worksheet workSheet = excelApp.Sheets.Add();

                    //heading for the columns
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        workSheet.Cells[1, (i + 1)] = dt.Columns[i].ColumnName;
                    }
                    //rows
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            workSheet.Cells[(i + 2), (j + 1)] = dt.Rows[i].ItemArray[j].ToString();
                        }
                    }
                }

                excelWorkBook.SaveCopyAs(folderPath);
                excelWorkBook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
                excelApp.Quit();
                Console.Write("Excel file saved!");
            }

            catch (Exception ex)
            {
                throw new Exception("ExportToExcel: \n" + ex.Message);
            }
        }
    }
 
Share this answer
 

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