Solved

Exporting a Datatable to Excel C#

Posted on 2007-12-05
5
13,590 Views
Last Modified: 2008-02-01
I need to put data in the first 5 columns of a datatable into excel usin C#. I tried to start writing it, but I am stuck. I am not an expert at this stuff by no means here is what I have so far:

app = new Excel.Application();
            workbook = app.Workbooks.Open(inputData.testPath, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows,
              "\t", false, false, 0, true, 0, true);

            Excel.Sheets sheets = workbook.Worksheets;

            Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);

            DataTable outputData = sdc.ResultData.Tables[0];

            Excel.Range theRange = FindPlaceToAppendData(worksheet);

            foreach (DataRow row in outputData.Rows)
            {
                //Insert a new Row in excel
                Excel.Range newRow = theRange.EntireRow;
                newRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown, false);

                //dunno if this code is even right
               //  HERE TRYING TO INSERT A ROW INTO EXCEL THEN FILL THE ROW WITH THE VALUES OF
               // THE ROW IN THE DATATABLE (THE FIRST 5 COLUMNS OF IT)
               // IF THERES A BETTER WAY BY ALL MEANS PLEASE HELP!
                int endIndex = worksheet.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell,Type.Missing).Column;

                for(int i=0;i<endIndex-1;i++)
                {
                   
                }

                    //Set the range value to the array.
                    theRange.set_Value(Missing.Value, saRet);
                }

            }

            app.Workbooks.Close();
            app.Quit();
            GC.Collect();
0
Comment
Question by:npl77
  • 3
  • 2
5 Comments
 
LVL 7

Expert Comment

by:bungHoc
ID: 20413644
Try this:
public void ToExcel(DataTable dataTable)

{

      string sData = "";

      for(int i = 0; i < dataTable.Columns.Count; i++)

      {

            sData += dataTable.Columns[i].ToString() + "\t";

      }

      sData += "\r\n";

      

      for(int i = 0; i < dataTable.Rows.Count; i++)

      {

            for(int j = 0; j < dataTable.Columns.Count; j++)

            {

                  sData += dataTable.Rows[i][j] + "\t";

            }

            sData += "\r\n";

      }
 

      System.Windows.Forms.Clipboard.SetDataObject(sData);                    
 

      xlsExcel = new Excel.Application();

      xlsBooks = (Excel.Workbooks)m_objExcel.Workbooks;

      xlsBook = (Excel._Workbook)(m_objBooks.Add(m_objOpt));
 

      xlsSheets = (Excel.Sheets)m_objBook.Worksheets;

      xlsSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));

      xlsRange = m_objSheet.get_Range("A1", m_objOpt);

      xlsSheet.Paste(m_objRange, false);
 

      // Save the workbook      

}

Open in new window

0
 

Author Comment

by:npl77
ID: 20421092
what is m_objOpt?
0
 

Author Comment

by:npl77
ID: 20421141
also what is m_objRange
0
 

Author Comment

by:npl77
ID: 20421281
this solution is pasting everything in column A1, the needs to go in like this:

Preview of dataTable:

"Data1"     "Data2"     "Data3"   "Data4"    "Data5"
   a                b                 c             d             e
   f                 g                 h             i               j
   k                 l                  m            n              o
...
Excel should look like this:

in row 1 are the headers are already there:
"Data1"     "Data2"     "Data3"  
   a                b                 c          
   f                 g                 h          
   k                 l                  m
...
           
0
 
LVL 7

Accepted Solution

by:
bungHoc earned 500 total points
ID: 20440082
Been on vacation last week. Sorry for getting back to you late. This is what I forgot to give you ;)


private Excel.Application m_objExcel =  null;

private Excel.Workbooks m_objBooks = null;			

private Excel._Workbook m_objBook = null;		

private Excel.Sheets m_objSheets = null;

private Excel._Worksheet m_objSheet = null;

private Excel.Range m_objRange =  null;

private object m_objOpt = System.Reflection.Missing.Value;

Open in new window

0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Image(2) 3 26
TT Column Arrange 10 28
Dynamic Excel Countdown Graphic 21 21
Macro Excel - Multiple If conditions 2 8
A little background as to how I came to I design this code: Around 5 years ago I designed an add-in that formatted Excel files to a corporate standard, applying different cell colours and font type depending on whether the cells contained inputs,…
Approximate matching with VLOOKUP and MATCH seems to me to be a greatly under-used technique, and one which is vital for getting good performance out of large lookups. Until recently I would always have advised using an exact match for simplicity an…
This Micro Tutorial demonstrates how to create Excel charts: column, area, line, bar, and scatter charts. Formatting tips are provided as well.
This Micro Tutorial will demonstrate how to create pivot charts out of a data set. I also added a drop-down menu which allows to choose from different categories in the data set and the chart will automatically update.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now