How to export a dataview to Excel?

How to export a dataview to excel? It requires the Tab Name and header for each column.
LVL 1
chuang4630Asked:
Who is Participating?
 
dfu23Commented:
Hello chuang4630,

The simplest way would be to iterate through the data and output it in Comma Separated Value (CSV) format.

Regards,
dfu23
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
bungHocConnect With a Mentor Commented:
Yup... I also agree with export to CSV format coz I've had problems with different Office version.

Here is to CSV:

private string ToCSV(DataTable dataTable)
{
      StringBuilder sb = new StringBuilder();      
      foreach (DataColumn column in dataTable.Columns)
      {
            sb.Append(column.ColumnName + ',');
      }            
      sb.Append("\r\n");
      foreach (DataRow row in dataTable.Rows)
      {
            foreach (DataColumn column in dataTable.Columns)
            {
                  sb.Append(row[column].ToString() + ',');
            }                  
            sb.Append("\r\n");
      }      
      return sb.ToString();
}

But if you need to Excel:

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      
}

0
 
nisarkhanConnect With a Mentor Commented:
0
 
dfu23Commented:
Just curious,
Why was my comment not selected as one to split the points with?
0
 
Computer101Commented:
Forced accept.

Computer101
EE Admin
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.