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.

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

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

[/code]

Please the  are with errors
3
Contributors
2
Replies
5
Views
8 Years
Discussion Span
Last Post by jatin24
0

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?

0

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.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.