Solved

Exporting a Datatable to Excel C#

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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
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…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

707 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