Solved

Exporting a Datatable to Excel C#

Posted on 2007-12-05
5
13,599 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Generating a graph via Excel 3 27
ms office troubleshooting for users 8 36
C#  Radio button search for Date not DateTime 4 35
Excel macro runs twice 13 51
Improved? Move/Copy Add-in Replacement - How to avoid the annoying, “A formula or sheet you want to move or copy contains the name XXX, which already exists on the destination worksheet.” David Miller (dlmille)  It was one of those days… I wa…
Workbook link problems after copying tabs to a new workbook? David Miller (dlmille) Intro Have you either copied sheets to a new workbook, and after having saved and opened that workbook, you find that there are links back to the original sou…
This Micro Tutorial will demonstrate on a Mac how to change the sort order for chart legend values and decrpyt the intimidating chart menu.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

920 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

17 Experts available now in Live!

Get 1:1 Help Now