ahmed salah

ahmed salah

  • 1.6k
  • 530
  • 123.2k

How to create excel file using c# windows form

Jan 21 2017 11:11 AM
I try to create excel file using c# windows form visual studio 2015
i need to create excel file with excel 2007 with extension xlsx
after i click the button and got to path i need to create i not found file found in path
so that what is wrong in code bellow :
  1. public Boolean AddExcelRow2007(String strFilePath)  
  2.        {  
  3.            if (!File.Exists(strFilePath)) return false;  
  4.            string strExcelConn = "Provider = Microsoft.ACE.OLEDB.12.0;" +  
  5.    "Data Source =" +strFilePath + "; Excel 12.0; HDR = YES;";  
  6.            OleDbConnection connExcel = new OleDbConnection(strExcelConn);  
  7.            OleDbCommand cmdExcel = new OleDbCommand();  
  8.            try  
  9.            {  
  10.                cmdExcel.Connection = connExcel;  
  11.   
  12.                //Check if the Sheet Exists  
  13.                connExcel.Open();  
  14.                DataTable dtExcelSchema;  
  15.                dtExcelSchema =  
  16.                connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);  
  17.                connExcel.Close();  
  18.                DataRow[] dr =  
  19.          dtExcelSchema.Select("TABLE_NAME = 'tblData'");  
  20.          
  21.        //if not Create the Sheet  
  22.                if (dr == null || dr.Length == 0)  
  23.                {  
  24.                    cmdExcel.CommandText = "CREATE TABLE[tblData]" +  
  25.            " (ID varchar(10), Name varchar(50));";  
  26.                    connExcel.Open();  
  27.                    cmdExcel.ExecuteNonQuery();  
  28.                    connExcel.Close();  
  29.                }  
  30.   
  31.                //Add New Row to Excel File  
  32.                cmdExcel.CommandText = "INSERT INTO[tblData]" + "(ID, Name) values('0', 'Start')";  
  33.   
  34.   
  35.                connExcel.Open();  
  36.                cmdExcel.ExecuteNonQuery();  
  37.                connExcel.Close();  
  38.                return true;  
  39.            }  
  40.            catch  
  41.            {  
  42.                return false;  
  43.            }  
  44.            finally  
  45.            {  
  46.                cmdExcel.Dispose();  
  47.                connExcel.Dispose();  
  48.            }  
  49.        }  
and after that i call
  1. private void button6_Click_1(object sender, EventArgs e)  
  2.        {  
  3.              
  4.           AddExcelRow2007("D:\\Book300.xlsx");  
  5.        }  
But excel file not created
so that what is wrong in code above 

Answers (5)