계층 구조 SPList를 Excel로 내보내기
                                            
 6304 단어  Excel
                    
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.Interop.Excel;
using System.Data;
using System.Web;
namespace NuctechProject.Layouts.Settings
{
    public partial class ToExcel : LayoutsPageBase
    {
        private static readonly string _rootUrl = HttpContext .Current.Request.Url.Scheme + "://" +
                                                  HttpContext.Current.Request.Url.Host;
        private static readonly string weburl = _rootUrl + "/" ;
        private readonly string StrUrl = weburl + "newTemplate/"; // 
        protected void Page_Load(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (var site = new SPSite(StrUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        // DataTable, , 
                        var dt = new System.Data.DataTable();
                        dt.Columns.Add( " " , typeof( string));
                        dt.Columns.Add( " " , typeof( string));
                        dt.Columns.Add( " " , typeof( string));
                        dt.Columns.Add( "ceng", typeof (string)); // , , 
                        SPList spList = web.Lists["TastTemp" ];
                        dt = GetDataTable(0, spList, dt, 1);
                        DataTabletoExcel(dt, @"C:\Users\Administrator\Desktop\strTemplateFileName.xlsx" );
                    }
                }
                ;
            });
        }
        public static void DataTabletoExcel(System.Data. DataTable tmpDataTable, string strFileName)
        {
            if (tmpDataTable == null )
                return;
            int rowNum = tmpDataTable.Rows.Count;
            int columnNum = tmpDataTable.Columns.Count;
            int rowIndex = 1;
            int columnIndex = 0;
            int cengMax = 0;
            cengMax = Convert.ToInt32(tmpDataTable.Compute("max(ceng)" , ""));
            int cengValue = cengMax - 1;
            Microsoft.Office.Interop.Excel. Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            xlApp.DefaultFilePath = "";
            xlApp.DisplayAlerts = true;
            xlApp.SheetsInNewWorkbook = 1;
            Workbook xlBook = xlApp.Workbooks.Add(true );
            // 
            for (int i = 0; i < (columnNum + cengValue); i++)
            {
                if (i == 1)
                {
                    xlApp.Cells[1, i] = tmpDataTable.Columns[i - 1].ColumnName;
                }
                if (i <= cengMax && i > 1)
                {
                    xlApp.Cells[1, i] = GetCapital(i - 1) + " " ;
                }
                if (i > cengMax)
                {
                    xlApp.Cells[1, i] = tmpDataTable.Columns[(i - cengMax)].ColumnName;
                }
            }
            // DataTable Excel 
            for (int i = 0; i < rowNum; i++)
            {
                rowIndex++;
                columnIndex = 0;
                for (int j = 0; j < (columnNum - 1); j++)
                {
                    if (j < 1)
                    {
                        int ceng = Convert .ToInt16(tmpDataTable.Rows[i][columnNum - 1].ToString());
                        xlApp.Cells[i + 2, ceng] = tmpDataTable.Rows[i][j].ToString();
                    }
                    if (j >= 1)
                    {
                        xlApp.Cells[i + 2, j + cengMax] = tmpDataTable.Rows[i][j].ToString();
                    }
                    columnIndex++;
                }
            }
            xlApp.get_Range((Microsoft.Office.Interop.Excel. Range)xlApp.Cells[1, 1], (Microsoft.Office.Interop.Excel.Range )xlApp.Cells[1, Convert.ToInt16(columnNum + cengValue - 1)]).Interior.ColorIndex = 16;
            xlApp.get_Range((Microsoft.Office.Interop.Excel. Range)xlApp.Cells[1, 1], (Microsoft.Office.Interop.Excel.Range )xlApp.Cells[10000, 100]).EntireColumn.AutoFit();// 
            xlBook.SaveCopyAs(strFileName);
        }
        /// <summary>
        ///  
        /// </summary>
        /// <param name="item"></param>
        /// <param name="parentKey"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public static System.Data.DataTable GetDataTable( int parentId, SPList list, System.Data.DataTable dt, int ceng)
        {
            SPQuery query = new SPQuery();
            query.Query = @"<Where>
                          <Eq>
                             <FieldRef Name='PID' />
                             <Value Type='Number'>" + parentId.ToString() + @"</Value>
                          </Eq>
                       </Where>" ;
            SPListItemCollection items = list.GetItems(query);
            foreach (SPListItem item in items)
            {
                string taskName = item["TaskName" ].ToString();
                string assignedTo = item["AssignedTo" ].ToString().Substring(item["AssignedTo"].ToString().LastIndexOf( "#") + 1);
                string status = item["Status" ].ToString();
                dt.Rows.Add(taskName, assignedTo, status, ceng.ToString());
                dt = GetDataTable(item.ID, list, dt, ceng + 1);
            }
            return dt;
        }
        public static string GetCapital( int number)
        {
            switch (number)
            {
                case 1:
                    return " " ;
                case 2:
                    return " " ;
                case 3:
                    return " " ;
                case 4:
                    return " " ;
                case 5:
                    return " " ;
            }
            return " " ;
        }
    }
}
  이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Excel Grep toolExcel Grep tool ■히나가타 ■ 시트 구성 ExcelGrep.cls...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.