C# .NET - how to export treeview data to excel

Asked By pranali shah
09-Sep-08 08:57 AM
end of post

solution code in C#  solution code in C#

09-Sep-08 09:07 AM

Hi,

Please refer to the following functions. It will be helpful to you. Also refer to http://msdn.microsoft.com/en-us/library/aa192488(office.11).aspx for different source codes snap shots.

static string fc;
Static OracleConnection Conn = new OracleConnection("bla bla");
protected void Page_Load(object sender, EventArgs e)
{
  if (Page.IsPostBack)
    fc = ((DropDownList)((Page)sender).FindControl("ddl1")).SelectedValue.ToString();
  else
    { if (Conn.State != ConnectionState.Open) Conn.Open(); }
}
protected void ddl1_DataBound(object sender, EventArgs e)
{
  if ( ! Page.IsPostBack )
    fc = ((DropDownList)sender).SelectedValue.ToString();
}
protected void pbFind_Click(object sender, EventArgs e)
{
  DateTime dt1 = DateTime.Now;
  TreeView1.Nodes.Clear();
  TreeNode tn = new TreeNode(ddl1.SelectedItem.ToString());
  TreeView1.Nodes.Add(tn);
  GetNodes(fc, tn);
  DateTime dt2 = DateTime.Now;
  TimeSpan ts = dt2 - dt1;
  if ( ts.Seconds <= 1 )
    Label1.Text = "Time to execute: " + ts.Seconds.ToString() + " second!!";
  else
    Label1.Text = "Time to execute: " + ts.Seconds.ToString() + " seconds!!";
}
protected void GetNodes(string Parent, TreeNode Tn)
{
  string Sql = "select failurecode, failurelist, parent, description from failurecode";
  OracleCommand Cmd = new OracleCommand(Sql, Conn);
  OracleDataReader Dr;
  Dr = Cmd.ExecuteReader();
  while (Dr.Read())
  {
    GridView1.DataSource = Dr;
    TreeNode tn = new TreeNode(Dr[0].ToString() + " (" + Dr[3].ToString() + ")", Dr[0].ToString());
    Tn.ChildNodes.Add(tn);
    if (! string.IsNullOrEmpty(Dr[1].ToString()))
    {
      Parent = Dr[1].ToString();
      GetNodes(Parent, tn);
    }
  }
  Dr.Close();
}
  private void btnGo_Click(object sender, EventArgs e)
        {
            string csvData = "";
 
            BuildCSV(treeView1.Nodes, ref csvData, 0);
 
            using (StreamWriter writer = new StreamWriter(@"C:\ExportedTree.csv"))
            {
                writer.Write(csvData);
            }
        }
 
        private void BuildCSV(TreeNodeCollection nodes, ref string csvData, int depth)
        {
            foreach (TreeNode node in nodes)
            {
                csvData = csvData + new String(',', depth) + node.Text + "\n";
 
                if (node.Nodes.Count > 0)
                    BuildCSV(node.Nodes, ref csvData, depth+1);
            }

Regards,

Paresh

how to export treeview data to excel  how to export treeview data to excel

09-Sep-08 12:28 PM

Hi,

You can loop the nodes of TreeView and put the node value/text into the excel file by writing excel. 

The below thread is about exporting the data from table to excel, and there is an approach for writing a excel file with data from dataset.

http://forums.asp.net/t/1214938.aspx

So you can convert nodes in TreeView to dataset first.

    private void convertTreeViewToDataSet()
    {
        DataTable dt = new DataTable("Values");
        dt.Columns.Add("text", Type.GetType("System.String"));
        for (int i = 0; i < TreeView1.Nodes.Count; i++)
        {
            DataRow dr = dt.NewRow();
            dr["text"] = TreeView1.Nodes[i].Value;
            dt.Rows.Add(dr);
        }
    }

You should adjust the above codes to meet your TreeView nodes format.

And then use the below approach to write to excel file with dataset:

    private void convertToExcel(DataSet dsBook)
    {
        try
        {

            int rows = dsBook.Tables[0].Rows.Count + 1;
            int cols = dsBook.Tables[0].Columns.Count;


            string ExcelFileName = Path.Combine(Request.PhysicalApplicationPath, "abcd.xls");
            if (File.Exists(ExcelFileName))
            {
                File.Delete(ExcelFileName);
            }
            StreamWriter writer = new StreamWriter(ExcelFileName, false);
            writer.WriteLine("");
            writer.WriteLine("");
            writer.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
            writer.WriteLine(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
            writer.WriteLine(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
            writer.WriteLine(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
            writer.WriteLine(" xmlns:html=\"http://www.w3.org/TR/REC-html40/\">");
            writer.WriteLine(" <DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">");
            writer.WriteLine("  <Author>Automated Report Generator Example</Author>");
            writer.WriteLine(string.Format("  <Created>{0}T{1}Z</Created>", DateTime.Now.ToString("yyyy-mm-dd"), DateTime.Now.ToString("HH:MM:SS")));
            writer.WriteLine("  <Company>51aspx.com</Company>");
            writer.WriteLine("  <Version>11.6408</Version>");
            writer.WriteLine(" </DocumentProperties>");
            writer.WriteLine(" <ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">");
            writer.WriteLine("  <WindowHeight>8955</WindowHeight>");
            writer.WriteLine("  <WindowWidth>11355</WindowWidth>");
            writer.WriteLine("  <WindowTopX>480</WindowTopX>");
            writer.WriteLine("  <WindowTopY>15</WindowTopY>");
            writer.WriteLine("  <ProtectStructure>False</ProtectStructure>");
            writer.WriteLine("  <ProtectWindows>False</ProtectWindows>");
            writer.WriteLine(" </ExcelWorkbook>");
            writer.WriteLine(" <Styles>");
            writer.WriteLine("  <Style ss:ID=\"Default\" ss:Name=\"Normal\">");
            writer.WriteLine("   <Alignment ss:Vertical=\"Bottom\"/>");
            writer.WriteLine("   <Borders/>");
            writer.WriteLine("   <Font/>");
            writer.WriteLine("   <Interior/>");
            writer.WriteLine("   <Protection/>");
            writer.WriteLine("  </Style>");
            writer.WriteLine("  <Style ss:ID=\"s21\">");
            writer.WriteLine("   <Alignment ss:Vertical=\"Bottom\" ss:WrapText=\"1\"/>");
            writer.WriteLine("  </Style>");
            writer.WriteLine(" </Styles>");
            writer.WriteLine(" <Worksheet ss:Name=\"MyReport\">");
            writer.WriteLine(string.Format("  <Table ss:ExpandedColumnCount=\"{0}\" ss:ExpandedRowCount=\"{1}\" x:FullColumns=\"1\"", cols.ToString(), rows.ToString()));
            writer.WriteLine("   x:FullRows=\"1\">");

            //generate title
            writer.WriteLine("<Row>");
            foreach (DataColumn eachCloumn in dsBook.Tables[0].Columns)
            {
                writer.Write("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">");
                writer.Write(eachCloumn.ColumnName.ToString());
                writer.WriteLine("</Data></Cell>");
            }
            writer.WriteLine("</Row>");

            //generate data
            foreach (DataRow eachRow in dsBook.Tables[0].Rows)
            {
                writer.WriteLine("<Row>");
                for (int currentRow = 0; currentRow != cols; currentRow++)
                {
                    writer.Write("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">");
                    writer.Write(eachRow[currentRow].ToString());
                    writer.WriteLine("</Data></Cell>");
                }
                writer.WriteLine("</Row>");
            }
            writer.WriteLine("  </Table>");
            writer.WriteLine("  <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
            writer.WriteLine("   <Selected/>");
            writer.WriteLine("   <Panes>");
            writer.WriteLine("    <Pane>");
            writer.WriteLine("     <Number>3</Number>");
            writer.WriteLine("     <ActiveRow>1</ActiveRow>");
            writer.WriteLine("    </Pane>");
            writer.WriteLine("   </Panes>");
            writer.WriteLine("   <ProtectObjects>False</ProtectObjects>");
            writer.WriteLine("   <ProtectScenarios>False</ProtectScenarios>");
            writer.WriteLine("  </WorksheetOptions>");
            writer.WriteLine(" </Worksheet>");
            writer.WriteLine(" <Worksheet ss:Name=\"Sheet2\">");
            writer.WriteLine("  <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
            writer.WriteLine("   <ProtectObjects>False</ProtectObjects>");
            writer.WriteLine("   <ProtectScenarios>False</ProtectScenarios>");
            writer.WriteLine("  </WorksheetOptions>");
            writer.WriteLine(" </Worksheet>");
            writer.WriteLine(" <Worksheet ss:Name=\"Sheet3\">");
            writer.WriteLine("  <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
            writer.WriteLine("   <ProtectObjects>False</ProtectObjects>");
            writer.WriteLine("   <ProtectScenarios>False</ProtectScenarios>");
            writer.WriteLine("  </WorksheetOptions>");
            writer.WriteLine(" </Worksheet>");
            writer.WriteLine("</Workbook>");
            writer.Close();
            Response.Write("<script language=\"javascript\">" + "alert('" + "convert completed!')" + "</script>");
        }
        catch (Exception ex)
        {
            Response.Write("<script language=\"javascript\">" + "alert('" + "error! " + ex.Message + "')" + "</script>");
        }
    
    }

 

Hope it helps.

Export TreeView to Excel in Two Ways  Export TreeView to Excel in Two Ways

03-Oct-08 06:48 AM
' There is two way  we can export to excel
'1  Export treeview to Excel treeview control
'2 Export treeview to excel sheet

Imports System
Imports System.Reflection ' For Missing.Value and BindingFlags
Imports System.Runtime.InteropServices ' For COMException
Imports Microsoft.Office.Interop.Excel  // in Add Reference, select COM tab, there  Microsoft Excel 11. excel 2003 has to install



Dim oOLE As OLEObject
    Dim intRow As Int32 = 1
    Dim intCol As Int16 = 1
    Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet

    Public Sub exportToExcelSheet()
        wSheet.Cells.Item(intRow, intCol) = trvEntity.Nodes(0).ToolTip()
        ColorChanging(wSheet.Cells.Item(intRow, intCol))
        intCol = intCol + 1
        For Each node As TreeNode In trvEntity.Nodes
            SaveNodeToSheet(node.ChildNodes)
        Next
    End Sub

    Private Sub SaveNodeToSheet(ByVal tnc As TreeNodeCollection)
        For Each node As TreeNode In tnc
            intRow = intRow + 1
            If (node.ChildNodes.Count > 0) Then
                intCol = CellPos(node.ValuePath())
                intRow = intRow + 1
                wSheet.Cells.Item(intRow, intCol) = node.ToolTip()
                SaveNodeToSheet(node.ChildNodes)
            Else
                intCol = CellPos(node.ValuePath())
                wSheet.Cells.Item(intRow, intCol) = node.ToolTip()
            End If
        Next
    End Sub

    Private Function CellPos(ByVal strPath As String) As Int16
        Dim intPos As Int16
        Dim strSplit As String() = strPath.Split(CChar("/"))
        intPos = strSplit.GetUpperBound(0)
        Return intPos + 1
    End Function

    Public Sub exportToTreeControl()
        oOLE.Object.Nodes.Add(, , trvEntity.Nodes(0).ToolTip(), trvEntity.Nodes(0).ToolTip())
        For Each node As TreeNode In trvEntity.Nodes
            SaveNodeToTreeControl(node.ChildNodes)
        Next
    End Sub

    Private Sub SaveNodeToTreeControl(ByVal tnc As TreeNodeCollection)
        For Each node As TreeNode In tnc
            If (node.ChildNodes.Count > 0) Then
                With oOLE.Object.Nodes.Add(node.Parent.Value, 4, node.Value, node.ToolTip())
                    .ForeColor = RGB(200, 0, 0)
                End With
                SaveNodeToTreeControl(node.ChildNodes)
            Else
                oOLE.Object.Nodes.Add(node.Parent.Value, 4, node.Value, node.ToolTip()).ForeColor = RGB(0, 0, 100)
            End If
        Next
    End Sub


    Private Sub ExcelExport(ByVal intTreeOrExcel As Int16)

        Dim strFileName As String = "c:\xlFileName.xls"
        Dim blnFileOpen As Boolean = False

        Dim excel As New Microsoft.Office.Interop.Excel.ApplicationClass
        Dim wBook As Microsoft.Office.Interop.Excel.Workbook

        wBook = excel.Workbooks.Add()
        wSheet = CType(wBook.ActiveSheet(), Worksheet)

        Dim colIndex As Integer = 0
        Dim rowIndex As Integer = 0

        If intTreeOrExcel = 1 Then
            oOLE = wSheet.OLEObjects.Add(ClassType:="MSComctlLib.TreeCtrl.2", _
            Left:=0, Top:=0, Width:=600, Height:=400)

            With oOLE
                .Name = "TreeView2"
                .Object.LineStyle = 1
                .Object.Font = "Comic Sans MS"
                .Object.Font.Size = "10"
                .Object.Style = 7
                .Object.Appearance = 0
                .Object.HideSelection = False
                .Object.HotTracking = True
                .Object.LabelEdit = 1
            End With
            exportToTreeControl()
            oOLE.Enabled = True
        Else
            exportToExcelSheet()
        End If

        wSheet.Columns.AutoFit()

        Try
            Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(strFileName)
            fileTemp.Close()
        Catch ex As Exception
            blnFileOpen = False
        End Try

        If System.IO.File.Exists(strFileName) Then
        // Error will come if file has opened already
            System.IO.File.Delete(strFileName)
        End If

        wBook.SaveAs(strFileName)
        excel.Workbooks.Open(strFileName)
        excel.Visible = True
    End Sub

    

'This will  export to excel
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        ExcelExport(1)
    End Sub

' It will create one treeview control in excel and export to the control
    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
        ExcelExport(0)
    End Sub
  Rafael Franco replied to Sebastian John
10-Jun-10 01:31 PM
in this line

oOLE = wSheet.OLEObjects.Add(ClassType:="MSComctlLib.TreeCtrl.2", _
            Left:=0, Top:=0, Width:=600, Height:=400)

i have an error, can you help me please?

Server Error in '/' Application.

Can not insert the object.

Description: An unhandled exception when you run the current web request. Check the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Runtime.InteropServices.COMException: Can not insert the object.

Source Error:


Line 258:
Line 259: If intTreeOrExcel = 1 Then
Line 260: oOLE = wSheet.OLEObjects.Add (ClassType: = "MSComctlLib.TreeCrtl.2", Left: = 0, Top: = 0, Width: = 600, Height: = 400)
Line 261:
Line 262: With oOLE

Source File: E: \ Projects \ UsPermisosVB \ UsPermisosVB \ Default.aspx.vb Line: 260

Stack Trace:


[COMException (0x800a03ec): Can not insert the object.]
   
Microsoft.VisualBasic.CompilerServices.LateBinding.LateGet (Object o, Type objtype, String name, Object [] args, String [] paramName, Boolean [] CopyBack) +934
   
Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet (Object Instance, Type Type, String MemberName, Object [] Arguments, String [] ArgumentNames, Type [] TypeArguments, Boolean [] CopyBack) +205
   
UsPermisosVB._Default.ExcelExport (Int16 intTreeOrExcel) in E: \ Projects \ UsPermisosVB \ UsPermisosVB \ Default.aspx.vb: 260
   
UsPermisosVB._Default.Button1_Click (Object sender, EventArgs e) in E: \ Projects \ UsPermisosVB \ UsPermisosVB \ Default.aspx.vb: 297
   
System.Web.UI.WebControls.Button.OnClick (EventArgs e) +111
   
System.Web.UI.WebControls.Button.RaisePostBackEvent (String eventArgument) +110
   
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent (String eventArgument) +10
   
System.Web.UI.Page.RaisePostBackEvent (IPostBackEventHandler sourceControl, String eventArgument) +13
   
System.Web.UI.Page.RaisePostBackEvent (NameValueCollection postData) +36
   
System.Web.UI.Page.ProcessRequestMain (Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

Version Information: Microsoft. NET Framework: 2.0.50727.4927; ASP.NET Version: 2.0.50727.4927
Create New Account
help
Logging Service b9wt High Log retention limit reached. Log file 'C: \ Program Files \ Common Files \ Microsoft Shared \ Web Server Extensions \ 14 \ LOGS \ TRICOFLEX-20111030-0008.log' has been deleted. 11 / 13 e63e-4ee9-b396-3fc61e3e6b80 11 / 13 / 2011 00:08:31.87 w3wp.exe (0x0DB4) 0x0AB8 Excel Services Application Excel Calculation Services 8jg2 Medium ResourceManager.PerformCleanup: Memory Manager: CurrentSize = 536850432. 53fed7f1-b549-1a88-0000-000050f7b00c SharePoint Foundation Topology e5mc Medium WcfSendRequest: RemoteAddress: 'http: / / tricoflex:32843 / 7a4080d658ba42efa38ff6455cbc382b / BdcService.svc / http' Channel: 'Microsoft.SharePoint.BusinessData.SharedService.IBdcServiceApplication' Action: 'http: / / www.microsoft.com / Office / 2009 / BusinessDataCatalog / BusinessDataCatalogSharedService / GetLobSystemsLikeName' MessageId: 'urn:uuid:abbcffd4-6783-4121-86ca-a30f0afe866a' 5c243a60 hozetric.local:32843 / 7a4080d658ba42efa38ff6455cbc382b / bdcservice.svc / http' Channel: 'System.ServiceModel.Channels.ServiceChannel' Action: 'http: / / www.microsoft.com / Office / 2009 / BusinessDataCatalog / BusinessDataCatalogSharedService / GetLobSystemsLikeName' MessageId: 'urn:uuid:abbcffd4-6783-4121-86ca-a30f0afe866a' 5c243a60 SharePoint Foundation Topology e5mc Medium WcfSendRequest: RemoteAddress: 'http: / / tricoflex:32843 / 7a4080d658ba42efa38ff6455cbc382b / BdcService.svc / http' Channel: 'Microsoft.SharePoint.BusinessData.SharedService.IBdcServiceApplication' Action: 'http: / / www.microsoft.com / Office / 2009 / BusinessDataCatalog / BusinessDataCatalogSharedService / GetLobSystemsLikeName' MessageId: 'urn:uuid:677d0349-b6d5-40e5-81b0-44215e75a07a' 5c243a60
other are not processing. and am getting below one in log file as error cause: Microsoft Windows Installer 4.5 Update (x86) - Windows XP: [2] CGenericComponent::Install() expects the setup file for Microsoft Windows Installer 4.5 Update (x86) - Windows XP, but the file is not available. [08 ISetupManager::InternalInstallManager() with HRESULT -2147467259. [08 / 10 / 11, 14:26:00] VS70pgui: [2] DepCheck indicates Microsoft Windows Installer 4.5 Update (x86) - Windows XP is not installed. [08 / 10 / 11, 14:26:00] VS70pgui: [2] DepCheck indicates Microsoft Visual F# 2.0 Runtime was not attempted to be installed. [08 / 10 / 11, 14 26:00] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio Macro Tools was not attempted to be installed. [08 / 10 / 11, 14:26 not attempted to be installed. [08 / 10 / 11, 14:26:01] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio 2010 Professional - ENU was not attempted to be installed. [08 / 10 / 11, 14:26:01] VS70pgui: [2] DepCheck indicates Microsoft Web Deployment Tool (x86) was not attempted to be installed. [08 / 10 / 11, 14:26 01] VS70pgui: [2] DepCheck indicates Microsoft ASP.NET MVC 2 - Visual Studio 2010 Tools was not attempted to be installed. [08
mistake, but currently I am reading the logfiles placed under "c: \ program files \ common files \ microsoft shared \ web server extensions \ 12 \ logs". I don't find any relavant information regarding authentication EXE (0x0980) 0x0988 Windows SharePoint Services Database 880i High . . .tem.Data.SqlClient.SqlConnection.Open() bei Microsoft.SharePoint.Utilities.SqlSession.OpenConnection() 03 / 04 / 2010 13:53:11.35 OWSTIMER.EXE (0x0980) 0x0988 13:53:11.59 OWSTIMER.EXE (0x0980) 0x0988 Windows SharePoint Services Database 880k High bei Microsoft.SharePoint.Utilities.SqlSession.ExecuteReader(SqlCommand command, CommandBehavior behavior) bei Microsoft.SharePoint.Administration.SPConfigurationDatabase.FetchId(QualifiedObjectName qName) bei Microsoft.SharePoint.Administration.SPConfigurationDatabase.GetObject(String name, Guid parentId, Type type) bei Microsoft.SharePoint.Administration.SPConfigurationDatabase.get_Farm() bei Microsoft.SharePoint.Administration.SPFarm.FindLocal(SPFarm& farm, Boolean& isJoined) bei Microsoft.SharePoint.Administration.SPFarm.get_Local() bei Microsoft.SharePoint.Administration.SPServer.get_Local() bei Microsoft.SharePoint.Administration.SPTimerStore
2011 19:10:25.0731] [0] * ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** * [11 / 17 / 2011 19:10:25.0731] [0] Starting Microsoft Exchange Server 2010 Setup [11 / 17 / 2011 19:10:25.0731] [0] * ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** * [11 / 17 / 2011 Central Time (US & Canada). [11 / 17 / 2011 19:10:25.0731] [0] Operating System version: Microsoft Windows NT 6.1.7601 Service Pack 1. [11 / 17 / 2011 19:10:25.0731 17 / 2011 19:10:27.0135] [0] Exchange configuration container for the organization is 'CN = Microsoft Exchange, CN = Services, CN = Configuration, DC = mr238, DC = org'. [11 / 17 / 2011 19:10:27.0135] [0] Exchange organization container for the organization is 'CN = First Organization, CN = Microsoft Exchange, CN = Services, CN = Configuration, DC = mr238, DC = org'. [11 / 17 / 2011 19:10:27 EXCHANGE, CN = Servers, CN = Exchange Administrative Group (FYDIBOHF23SPDLT), CN = Administrative Groups, CN = First Organization, CN = Microsoft Exchange, CN = Services, CN = Configuration, DC = mr238, DC = org'. [11 / 17 / 2011 19:10:27 EXCHANGE, CN = Servers, CN = Exchange Administrative Group (FYDIBOHF23SPDLT), CN = Administrative Groups, CN = First Organization, CN = Microsoft Exchange, CN = Services, CN = Configuration, DC = mr238, DC = org'. [11 / 17 / 2011 19:10:27 15. [11 / 17 / 2011 19:11:17.0415] [0] Exchange Installation Directory : 'F: \ Program Files \ Microsoft \ Exchange Server \ V14'. [11 / 17 / 2011 19:11:17.0446] [0] Applying default role selection 17 / 2011 19:11:17.0477] [0] Setup will run from path 'F: \ Program Files \ Microsoft \ Exchange Server \ V14 \ '. [11 / 17 / 2011 19:11:17.0493] [0] InstallModeDataHandler has 0 DataHandlers