4

How can I export this data table to excel using: "Microsoft.Office.Interop.Excel" I have this code witch grabs all the data form Master table and want to export it to excel for better view, don't want to use datagrid. There are a lot of post regarding this topic I think, but usually just recommend using some ad on like "closedxml"

        OleDbConnection mycon;           
        DataTable Table = new DataTable("AllData");

        mycon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\jm11321\Documents\DB.mdb;Persist Security Info=False");

        string command = "Select *From Master";
        OleDbCommand oleDbCmd = new OleDbCommand(command,mycon);

        OleDbDataAdapter adapt = new OleDbDataAdapter(oleDbCmd);
        mycon.Open();
        adapt.Fill(Table);
        mycon.Close();

Any help is appreciated.

2 Answers 2

4

You have to import Microsoft.Office.Interop.Excel.dll library from here. Add new class file in your project say ExcelUtility. Just write down the following code in it.

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelDemo
{
    public class ExcelUtility
    {
        public static void CreateExcel(DataSet ds, string excelPath)
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            try
            {
                //Previous code was referring to the wrong class, throwing an exception
                xlApp = new Excel.Application();
                xlWorkBook = xlApp.Workbooks.Add(misValue);
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

                for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
                {
                    for (int j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
                    {
                        xlWorkSheet.Cells[i + 1, j + 1] = ds.Tables[0].Rows[i].ItemArray[j].ToString();
                    }
                }

                xlWorkBook.SaveAs(excelPath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();

                releaseObject(xlApp);
                releaseObject(xlWorkBook);
                releaseObject(xlWorkSheet);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch
            {
                obj = null;
            }
            finally
            {
                GC.Collect();
            }
        } 
    }
}

Now in main code just pass the dataset object and excel path as below.

ExcelUtility.CreateExcel(ds, "D:\\Demo.xls");

I have already tested and using this in my projects.

Sign up to request clarification or add additional context in comments.

3 Comments

I get an error in "Excel.Application xlApp;" error "Error 2 Interop type 'Microsoft.Office.Interop.Excel.ApplicationClass' cannot be embedded. Use the applicable interface instead." @Dinesh Maind
Edit-1 "Excel._Application xlApp = new Excel.Application();" this fixed that problem, but nothing seems to happen.
This code doesn't add Datatable column names to the exported Excel though
3

I know that there is already an answer, although here is another approach

 var workbook = new XLWorkbook();
        var worksheet = workbook.Worksheets.Add("Sample Sheet");
        worksheet.Cell("A1").Value = "Hello World!";
        workbook.SaveAs("HelloWorld.xlsx");

whats also really amazing about this approach is that you can put your dataset table or table into the workbook like such

 var wb = new XLWorkbook();

        var dataTable = GetTable("Information");

        // Add a DataTable as a worksheet
        wb.Worksheets.Add(dataTable);

        wb.SaveAs("AddingDataTableAsWorksheet.xlsx");

the dll is here

1 Comment

Just remember to add a table name to your dataset tables and datatables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.