Solved

Exporting a Datatable to Excel C#

Posted on 2007-12-05
5
13,634 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
parsing question on dynamic concatenation 3 34
Delete row if does not start with 0 43 39
Target.Address conflict in Excel VBA 3 25
Overwriting Named Ranges 13 35
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Some code to ensure data integrity when using macros within Excel. Also included code that helps secure your data within an Excel workbook.
This Micro Tutorial will demonstrate in Google Sheets how to use the HYPERLINK function to create live links inside your spreadsheet.
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.

730 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