Here you go

Thursday, July 10, 2014

Export Data To Excel Using C# / C Sharp


Export Data From Data Set / Data Table / Data Grid View to MS Excel:

You can export data from Data Set / Data Table / Data Grid View to MS Excel Using Following Function:


        public void ExportToExcel(string reportName, string parameter, string path, DataGridView dgv , string userName)
        {
            int i = 0;
            int j = 0;
            int col = 0;

            string folderPath = "";

         
            FolderBrowserDialog fbdExportFileLocation = new FolderBrowserDialog();
            if (fbdExportFileLocation.ShowDialog() == DialogResult.OK)
            {
                folderPath = fbdExportFileLocation.SelectedPath;
            }

            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;


            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);


            //  Report Name
            xlWorkSheet.Cells[1, 1] = reportName;

            //  Parameters
            xlWorkSheet.Cells[3, 1] = parameter;

            //
            xlWorkSheet.Cells[4, 1] = "User Name : " + userName;

            // Report Columns Heading
            for (col = 0; col <= dgv.ColumnCount - 1; col++)
            {

                xlWorkSheet.Cells[5, col + 1] = dgv.Columns[col].HeaderText.ToString().Replace('_',' ');
             
            }
         
            Excel.Range Rows = xlWorkSheet.get_Range("A1",  "A5");
            Rows.EntireRow.Font.Bold = true;

            Excel.Range Row1 = xlWorkSheet.get_Range("A1",  "A1");
            Row1.EntireRow.Font.Size = 16;

            for (i = 0; i <= dgv.RowCount - 1; i++)
            {
                for (j = 0; j <= dgv.ColumnCount - 1; j++)
                {
                    DataGridViewCell cell = dgv[j, i];
                    xlWorkSheet.Cells[i + 6, j + 1] = cell.Value;
                }

            }

            xlWorkBook.SaveAs(folderPath+"\\REPORT-"+reportName+".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

            MessageBox.Show("Excel file created, you can find the file on : " + folderPath + "\\REPORT-" + reportName + ".xls");
        }


Now you can convert code from Any Language to Other Language : Link

No comments:

Post a Comment

Thanks for making a comment.