Export to excel

SAINTJAB 0 Tallied Votes 368 Views Share

the code tries to export the table memberinfo to excel.

Hi guys, am new with C# but try to export a table named memberinfo to excel. 
I had this code from the net but have sat on it for three hours without being able
to make it work. First i want to know what to reference and then the code to use to 
export to excel. Please if possible try to comment on the code below. I am kind of got
used to it or can give a different one all together. Please help me.

private void btnexportfile_Click(object sender, EventArgs e)
            Excel.ApplicationClass excel = new ApplicationClass();

            DataTable table = memberinfo.Tables[0];
            int ColumnIndex = 0;
            foreach (Datacolumn col in table.Columns)
                excel.Cells[1, ColumnIndex] = col.ColumnName;
            int rowIndex = 0;
            foreach (DataRow row in table.Rows)
                ColumnIndex = 0;
                foreach (DataColumn col in table.Columns)
                    excel.Cells[rowIndex + 1, ColumnIndex] = row.Cells[col.ColumnName].Text;
            excel.Visible = true;
            Worksheet worksheet = (Worksheet)excel.ActiveSheet;


Please the  are with errors
DdoubleD 315 Posting Shark

I went and copied this code a couple of hours ago or so, then I got interrupted by a loooong phone call. Anyway, I can't resolve some definitions and I also forgot what I was thinking... Can you post an example with complete code that will compile?

jatin24 21 Junior Poster in Training

Try this:

Microsoft.Office.Interop.Excel.Application exc = new Microsoft.Office.Interop.Excel.Application();
            exc.Visible = true;
            _Workbook workbook;
            _Worksheet worksheet;
            Workbooks workbooks = exc.Workbooks;
            workbook = workbooks.Add(true);
            Sheets sheets = workbook.Worksheets;
            worksheet = (_Worksheet)sheets.get_Item(1);

            // start inserting your values here.
            Range range1 = worksheet.get_Range("A1", "A1");
            string[] array1 = new string[1];
            array1[0] = "Some text";
            Object[] args1 = new Object[1];
            args1[0] = array1;
            range1.GetType().InvokeMember("Value", System.Reflection.BindingFlags.SetProperty, null, range1, args1);

            // You can modify this above section of code accordingly and put it in a for/foreach loop to insert values at different locations.

Make sure to include the Microsoft Excel 12 Libraries before you do this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.