. NET 환경 에서 Excel 표를 내 보 내 는 두 가지 방식 과 두 가지 유형의 Excel 표를 가 져 오 는 것

79162 단어 Excel 내 보 내기
1. 엑셀 표를 내 보 내 는 두 가지 방식 중 두 가지 방식 은 XML 데이터 형식 을 내 보 내 는 엑셀 (즉, 저장 할 때 확장 자 를 'xls' 로 만 수정 할 수 있 음) 과 진정한 엑셀 두 가 지 를 말한다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml;

using Ipms.Server.Business;
using Ipms.Server.UI;
using Ipms.Server.UI.HttpExtension;
using Ipms.Server.UI.MISExtension;
using System.Xml.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.IO;

namespace Ipms.WebSite.Service.File
{
    /// <summary>
    /// Summary description for ExportWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class ExportWebService : WebServiceBase
    {

        //  XML  
        [WebMethod]
        public void SendData()
        {
            string excelTitle = Request.GetString("excelTitle");

            XmlDocument storeXmlDocument = new XmlDocument();
            XmlDocument columnsXmlDocument = new XmlDocument();
            storeXmlDocument.LoadXml(Request.GetString("contentStoreXml"));
            columnsXmlDocument.LoadXml(Request.GetString("selectColumns"));
            XDocument storeXDocument = XDocument.Load(new XmlNodeReader(storeXmlDocument));
            XDocument columnsXDocument = XDocument.Load(new XmlNodeReader(columnsXmlDocument));
            int columnsCount = Convert.ToInt16(columnsXDocument.Root.Elements().Single(p => p.Name.LocalName == "selectedCount").Value);

            string[][] columnsArrary = getColumnsArray(columnsXDocument);

            // excel     excelXml   
            var excelXml = getExcelXML(columnsArrary, columnsCount, storeXDocument, excelTitle);

            var guid = Guid.NewGuid();
            Context.Cache[guid.ToString()] = excelXml;
            Response.Write(guid);
        }

        private string[][] getColumnsArray(XDocument columns)
        {
            string[] nameArray = columns.Root.Elements().Single(p => p.Name.LocalName == "selectedName").Value.Split(',');
            string[] boxLabelArray = columns.Root.Elements().Single(p => p.Name.LocalName == "selectedBoxLabel").Value.Split(',');
            string[] renderArray = columns.Root.Elements().Single(p => p.Name.LocalName == "selectedRenderer").Value.Split(',');
            string[] widthArray = columns.Root.Elements().Single(p => p.Name.LocalName == "selectedWidth").Value.Split(',');
            string[][] columnsArray = new string[4][];
            columnsArray[0] = nameArray;
            columnsArray[1] = boxLabelArray;
            columnsArray[2] = renderArray;
            columnsArray[3] = widthArray;

            return columnsArray;
        }
        private StringBuilder getExcelXML(string[][] columnsArray, int columnsCount, XDocument storeXDocument, string ExcelTitle)
        {
            int worksheetHeight = 20;//Convert.ToInt16(storeXDocument.Root.Elements().First().Value) * 20 + 20;
            int worksheetWidth = 50;//columnsCount * 300 + 50;
            StringBuilder worksheetXml = creatWorksheet(columnsArray, columnsCount, storeXDocument, ExcelTitle);

            StringBuilder exportExcelXml = new StringBuilder();
            exportExcelXml.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            exportExcelXml.Append("<ss:Workbook xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:o=\"urn:schemas-microsoft-com:office:office\">");
            exportExcelXml.Append("<o:DocumentProperties><o:Title>");
            exportExcelXml.Append(ExcelTitle);
            exportExcelXml.Append("</o:Title></o:DocumentProperties>");
            exportExcelXml.Append("<ss:ExcelWorkbook>");
            exportExcelXml.Append("<ss:WindowHeight>");
            exportExcelXml.Append(worksheetHeight);
            exportExcelXml.Append("</ss:WindowHeight>");
            exportExcelXml.Append("<ss:WindowWidth>");
            exportExcelXml.Append(worksheetWidth);
            exportExcelXml.Append("</ss:WindowWidth>");
            exportExcelXml.Append("<ss:ProtectStructure>False</ss:ProtectStructure>");
            exportExcelXml.Append("<ss:ProtectWindows>False</ss:ProtectWindows>");
            exportExcelXml.Append("</ss:ExcelWorkbook>");
            exportExcelXml.Append("<ss:Styles>");
            exportExcelXml.Append("<ss:Style ss:ID=\"Default\">");
            exportExcelXml.Append("<ss:Alignment ss:Vertical=\"Top\" ss:WrapText=\"1\" />");
            exportExcelXml.Append("<ss:Font ss:FontName=\"arial\" ss:Size=\"10\" />");
            exportExcelXml.Append("<ss:Borders>");
            exportExcelXml.Append("<ss:Border ss:Color=\"#e4e4e4\" ss:Weight=\"1\" ss:LineStyle=\"Continuous\" ss:Position=\"Top\" />");
            exportExcelXml.Append("<ss:Border ss:Color=\"#e4e4e4\" ss:Weight=\"1\" ss:LineStyle=\"Continuous\" ss:Position=\"Bottom\" />");
            exportExcelXml.Append("<ss:Border ss:Color=\"#e4e4e4\" ss:Weight=\"1\" ss:LineStyle=\"Continuous\" ss:Position=\"Left\" />");
            exportExcelXml.Append("<ss:Border ss:Color=\"#e4e4e4\" ss:Weight=\"1\" ss:LineStyle=\"Continuous\" ss:Position=\"Right\" />");
            exportExcelXml.Append("</ss:Borders>");
            exportExcelXml.Append("<ss:Interior />");
            exportExcelXml.Append("<ss:NumberFormat />");
            exportExcelXml.Append("<ss:Protection />");
            exportExcelXml.Append("</ss:Style>");
            exportExcelXml.Append("<ss:Style ss:ID=\"title\">");
            exportExcelXml.Append("<ss:Borders />");
            exportExcelXml.Append("<ss:Font />");
            exportExcelXml.Append("<ss:Alignment ss:WrapText=\"1\" ss:Vertical=\"Center\" ss:Horizontal=\"Center\" />");
            exportExcelXml.Append("<ss:NumberFormat ss:Format=\"@\" />");
            exportExcelXml.Append("</ss:Style>");
            exportExcelXml.Append("<ss:Style ss:ID=\"headercell\">");
            exportExcelXml.Append("<ss:Font ss:Bold=\"1\" ss:Size=\"10\" />");
            exportExcelXml.Append("<ss:Alignment ss:WrapText=\"1\" ss:Horizontal=\"Center\" />");
            exportExcelXml.Append("<ss:Interior ss:Pattern=\"Solid\" ss:Color=\"#A3C9F1\" />");
            exportExcelXml.Append("</ss:Style>");
            exportExcelXml.Append("</ss:Styles>");
            exportExcelXml.Append(worksheetXml);
            exportExcelXml.Append("</ss:Workbook>");
            return exportExcelXml;
        }
        private StringBuilder creatWorksheet(string[][] columnsArray, int columnsCount, XDocument storeXDocument, string title)
        {
            int dataCount = Convert.ToInt16(storeXDocument.Root.Elements().First().Value);
            XElement listElement = storeXDocument.Root.Elements().Last();

            StringBuilder columnXml = new StringBuilder();
            StringBuilder headerXml = new StringBuilder();
            for (var i = 0; i < columnsCount; i++)
            {
                columnXml.Append("<ss:Column ss:AutoFitWidth=\"1\" ss:Width=\"");
                columnXml.Append(columnsArray[3][i]);
                columnXml.Append("\" />");
                headerXml.Append("<ss:Cell ss:StyleID=\"headercell\">");
                headerXml.Append("<ss:Data ss:Type=\"String\">");
                headerXml.Append(columnsArray[1][i]);
                headerXml.Append("</ss:Data>");
                headerXml.Append("<ss:NamedCell ss:Name=\"Print_Titles\" /></ss:Cell>");
            }
            StringBuilder headerDetailXml = getHeader(title, columnsCount, dataCount, headerXml, columnXml);
            headerDetailXml = appendHeaderDetailXml(listElement, headerDetailXml, columnsArray, columnsCount);
            StringBuilder resultXml = getResultXml(headerDetailXml);
            return resultXml;
        }
        private StringBuilder getHeader(string title, int columnsCount, int dataCount, StringBuilder headerXml, StringBuilder columnXml)
        {
            StringBuilder headerDetailXml = new StringBuilder();
            headerDetailXml.Append("<ss:Worksheet ss:Name=\"");
            headerDetailXml.Append(title);
            headerDetailXml.Append("\">");
            headerDetailXml.Append("<ss:Names>");
            headerDetailXml.Append("<ss:NamedRange ss:Name=\"Print_Titles\" ss:RefersTo=\"=\'");
            headerDetailXml.Append(title);
            headerDetailXml.Append("\'!R1:R2\" />");
            headerDetailXml.Append("</ss:Names>");
            headerDetailXml.Append("<ss:Table x:FullRows=\"1\" x:FullColumns=\"1\"");
            headerDetailXml.Append(" ss:ExpandedColumnCount=\"");
            headerDetailXml.Append(columnsCount + 2);
            headerDetailXml.Append("\" ss:ExpandedRowCount=\"");
            headerDetailXml.Append(dataCount + 1);
            headerDetailXml.Append("\">");
            headerDetailXml.Append(columnXml);
            headerDetailXml.Append("<ss:Row ss:AutoFitHeight=\"1\">");
            headerDetailXml.Append(headerXml);
            headerDetailXml.Append("</ss:Row>");

            return headerDetailXml;
        }
        private StringBuilder appendHeaderDetailXml(XElement listElement, StringBuilder headerDetailXml, string[][] columnsArray, int columnsCount)
        {
            foreach (XElement record in listElement.Elements())
            {
                headerDetailXml.Append("<ss:Row>");
                for (var j = 0; j < columnsCount; j++)
                {
                    string data = "";
                    //carlsirce   
                    var element = record.Elements().FirstOrDefault(e => e.Name.LocalName == columnsArray[0][j]) == null ? null : record.Elements().FirstOrDefault(e => e.Name.LocalName == columnsArray[0][j]);
                    if (element != null)
                        data = element.Value;

                    //string renderedData = renderData(data, columnsArray[2][j]);
                    headerDetailXml.Append("<ss:Cell ss:StyleID=\"Default\"><ss:Data ss:Type=\"String\">");
                    headerDetailXml.Append("<![CDATA[");
                    headerDetailXml.Append(data);
                    headerDetailXml.Append("]]>");
                    headerDetailXml.Append("</ss:Data></ss:Cell>");

                }
                headerDetailXml.Append("</ss:Row>");
            }

            return headerDetailXml;
        }
        private StringBuilder getResultXml(StringBuilder headerDetailXml)
        {
            StringBuilder resultXml = new StringBuilder();
            resultXml.Append(headerDetailXml);
            resultXml.Append("</ss:Table>");
            resultXml.Append("<x:WorksheetOptions>");
            resultXml.Append("<x:PageSetup>");
            resultXml.Append("<x:Layout x:CenterHorizontal=\"1\" x:Orientation=\"Landscape\" />");
            resultXml.Append("<x:Footer x:Data=\"Page &amp;P of &amp;N\" x:Margin=\"0.5\" />");
            resultXml.Append("<x:PageMargins x:Top=\"0.5\" x:Right=\"0.5\" x:Left=\"0.5\" x:Bottom=\"0.8\" />");
            resultXml.Append("</x:PageSetup>");
            resultXml.Append("<x:FitToPage />");
            resultXml.Append("<x:Print>");
            resultXml.Append("<x:PrintErrors>Blank</x:PrintErrors>");
            resultXml.Append("<x:FitWidth>1</x:FitWidth>");
            resultXml.Append("<x:FitHeight>32767</x:FitHeight>");
            resultXml.Append("<x:ValidPrinterInfo />");
            resultXml.Append("<x:VerticalResolution>600</x:VerticalResolution>");
            resultXml.Append("</x:Print>");
            resultXml.Append("<x:Selected />");
            resultXml.Append("<x:DoNotDisplayGridlines />");
            resultXml.Append("<x:ProtectObjects>False</x:ProtectObjects>");
            resultXml.Append("<x:ProtectScenarios>False</x:ProtectScenarios>");
            resultXml.Append("</x:WorksheetOptions>");
            resultXml.Append("</ss:Worksheet>");
            return resultXml;
        }
        //  EXCEL

        [WebMethod]
        public void ExportToXlsExcel()
        {
            var memberApplyIDs = Request.GetString("memberApplyIDs");

            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.RootFolder = Environment.SpecialFolder.Desktop;  //           
            fbd.Description = "       :";   //        

            var ids = memberApplyIDs.Split(',');

            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("    ", typeof(string));
            dt.Columns.Add("  ", typeof(string));
            dt.Columns.Add("  ", typeof(string));
            dt.Columns.Add("  ", typeof(string));
            dt.Columns.Add("  (  )", typeof(string));
            dt.Columns.Add("  ", typeof(string));
            dt.Columns.Add("  ", typeof(string));
            dt.Columns.Add("   (   )", typeof(string));
            dt.Columns.Add("   ", typeof(string));
            dt.Columns.Add("   (  )", typeof(string));
            dt.Columns.Add("    ", typeof(string));
            for (int i = 0; i < ids.Length - 1; i++)
            {
                var expertApplyItemID = Convert.ToInt32(ids[i]);
                var expertApplyItem = Database.MemberApplyItems.GetByID(expertApplyItemID);
                if (expertApplyItem != null)
                {
                    DataRow dr = dt.NewRow();
                    dr["ID"] = expertApplyItem.ID;
                    var constructPlanItem = Database.ConstructPlanItems.FirstOrDefault(c => c.MemberApplyItem == expertApplyItem);
                    if (constructPlanItem != null)
                        dr["    "] = constructPlanItem.DeviceNumber.ToString();
                    else
                        dr["    "] = "";
                    dr["  "] = expertApplyItem.ApplyDevice.DeviceName;
                    dr["  "] = expertApplyItem.Quantity.ToString();
                    dr["  "] = expertApplyItem.GetCompanys(expertApplyItem, Database);
                    dr["  (  )"] = (expertApplyItem.Quantity * expertApplyItem.ApplyDevice.UnitPrice / 1000000).ToString() + "." + (expertApplyItem.Quantity * expertApplyItem.ApplyDevice.UnitPrice % 1000000 / 100).ToString() + "  ";
                    dr["  "] = expertApplyItem.GetModels(expertApplyItem, Database);
                    dr["  "] = expertApplyItem.MemberApply.College.Name;
                    dr["   (   )"] = expertApplyItem.ApplyDevice.Configuration;
                    dr["   "] = expertApplyItem.ApplicantName;
                    dr["   (  )"] = (expertApplyItem.ApplyDevice.UnitPrice / 1000000).ToString() + "." + (expertApplyItem.ApplyDevice.UnitPrice % 1000000 / 100).ToString() + "  ";
                    dr["    "] = expertApplyItem.PhoneNumber.ToString();
                    dt.Rows.Add(dr);
                    dt.AcceptChanges();
                }
            }
            ExportExcel(dt);
        }

        private void ExportExcel(System.Data.DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0) return;
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                return;
            }
            System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
            worksheet.Name = "    ";
            Microsoft.Office.Interop.Excel.Range range;
            long totalCount = dt.Rows.Count;
            long rowRead = 0;
            float percent = 0;
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
                range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
                range.Interior.ColorIndex = 15;
                range.Font.Bold = true;
            }
            for (int r = 0; r < dt.Rows.Count; r++)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
                }
                rowRead++;
                percent = ((float)(100 * rowRead)) / totalCount;
            }

            workbook.Saved = true;

            FileInfo fileInfo = new FileInfo("D:\\      .xlsx");
            workbook.SaveCopyAs(fileInfo);
            workbook.Close(true, Type.Missing, Type.Missing);

            GetDataForStatisticExport1("D:\\      .xlsx", "      .xlsx");

        }
        private void GetDataForStatisticExport1(string filePath, string downloadName)
        {
            bool isIE = Convert.ToBoolean(Request["isIE"]);
            if (isIE)
                downloadName = HttpUtility.UrlEncode(downloadName, System.Text.Encoding.UTF8);

            FileInfo fileInfo = new FileInfo(filePath);
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();

            Response.AddHeader("Content-Disposition", "attachment;filename=" + downloadName);
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.AddHeader("Connection", "Keep-Alive");

            Response.ContentType = "data:application/vnd.ms-excel";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");

            Response.WriteFile(fileInfo.FullName);
            Response.Flush();
            Response.End();
        }
    }
}

2. 두 가지 유형의 Excel 을 가 져 옵 니 다. 그 중에서 두 가지 유형 은 xls 와 xlsx 라 는 두 가지 유형 을 말 합 니 다. 차 이 는 한 줄 의 코드 일 뿐 아래 파일 에 표지 가 있 습 니 다.
1、Import.asmx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

using Ipms.Server.UI;
using Ipms.Server.UI.HttpExtension;
using Ipms.Server.UI.MISExtension;
using Ipms.Server.UI.Packages;

using Ipms.Server.Business;
using Ipms.Server.Business.Common;

using Ipms.Server.DataExchange.ConstructPlanDeviceImport;

namespace Ipms.WebSite.Service.File
{
    /// <summary>
    /// Summary description for ImportWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class ImportWebService : WebServiceBase
    {
        [WebMethod]
        public void DeviceImport()
        {
            var postedFiles = Request.GetHttpFiles();
            var deviceReport = Request.GetDeviceReport(User, Database);
            deviceReport.Save(Database);
            var deviceReportInfo = string.Format("985 :{0},          ,  :{1},    :{2},ID:{3}", User.Name, deviceReport.ReportYear, deviceReport.FundSource, deviceReport.ID);
            BusinessLog.Write(User, UserIP, deviceReportInfo, this.GetType().FullName, "DeviceImport", Database);
            
            //    
            try
            {
                string logName = Context.ImportConstructPlanDevice(postedFiles[0], Request, deviceReport.ID);

                Response.Write("<html><body>{ success: true, LogDocumentName: '" + logName + "' }</body></html>");
            }
            catch
            {
                Response.Write("<html><body>{ success: true, LogDocumentName: 'false' }</body></html>");

            }
        }
    }
}

2、FileUpLoadHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Data;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Reflection;
using System.IO;
using System.Web;
using Microsoft.Office.Interop.Excel;

namespace Ipms.Server.DataExchange
{
    /// <summary>
    ///       
    /// </summary>
    public static class FileUpLoadHelper
    {
        /// <summary>
        ///         
        /// </summary> 
        public const string POSTED_FILE_ROOT_DIRECTORY = @"/IpmsDocument\";
        /// <summary>
        ///  EXCEL     (  dataset )
        /// </summary>
        /// <param name="postedFile"></param>
        /// <param name="context"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static DataSet GetDataFromUploadFile(this HttpPostedFile postedFile, HttpContext context, string tableName)
        {
            string directory = context.Server.MapPath(POSTED_FILE_ROOT_DIRECTORY);

            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);

            string filename = postedFile.FileName;
            //         
            postedFile.SaveAs(context.Server.MapPath(POSTED_FILE_ROOT_DIRECTORY) + filename);

            string conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + context.Server.MapPath(POSTED_FILE_ROOT_DIRECTORY) + filename + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
            conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + context.Server.MapPath(POSTED_FILE_ROOT_DIRECTORY) + filename + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";

            //string sqlin = "SELECT * FROM [" + "ConstructPlanDevice" + "$]";
            //OleDbCommand oleCommand = new OleDbCommand(sqlin, new OleDbConnection(conn));

            //OleDbDataAdapter adapterIn = new OleDbDataAdapter(oleCommand);
            //DataSet dsIn = new DataSet();
            //adapterIn.Fill(dsIn, tableName);


            OleDbConnection conn1 = new OleDbConnection(conn);
            conn1.Open();
            string name = conn1.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0][2].ToString().Trim();
            OleDbDataAdapter odda = new OleDbDataAdapter("select * from ["+name+"]", conn1);
            DataSet dsIn1 = new DataSet();
            odda.Fill(dsIn1, tableName);
            conn1.Close();
            return dsIn1;
        }

        /// <summary>
        ///        
        /// </summary>
        /// <param name="context"></param>
        /// <param name="filename"></param>
        public static void DeleteFile(this HttpContext context, string filename)
        {
            FileInfo file = new FileInfo(context.Server.MapPath(POSTED_FILE_ROOT_DIRECTORY) + filename);
            if (file.Exists)
                file.Delete();
        }
    }
}

3、ConstructPlanDeviceImport.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Data;
using System.IO;

using Ipms.Server.Business;
using Ipms.Server.Business.Devices;
using Ipms.Server.Business.MemberApplys;
using Ipms.Server.Business.Packages;

using MIS.Common;
using MIS.Common.Query;
using Ipms.Server.UI;

using Ipms.Server.UI.MISExtension;
using Ipms.Server.UI.HttpExtension;

using Ipms.Server.DataAccess;
using Ipms.Server.Business.Users;
using Ipms.Server.Business.Projects;

namespace Ipms.Server.DataExchange.ConstructPlanDeviceImport
{
    /// <summary>
    ///   985      
    /// </summary>
    public static class ConstructPlanDeviceImport
    {
        /// <summary>
        ///   985      
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="postedFile"></param>
        /// <param name="request"></param>
        /// <param name="deviceReportID"></param>
        /// <returns></returns>
        public static string ImportConstructPlanDevice(this HttpContext httpContext, HttpPostedFile postedFile, HttpRequest request, int deviceReportID)
        {
            //return string.Empty;
            IDatabase database = Database.New();
            string logName = "ConstructPlanDeviceImportLog" + DateTime.Now.ToLongDateString().ToString() + Guid.NewGuid().ToString();
            var writer = httpContext.GetLogWriter(logName);

            string fileName = "ConstructPlanDevice";
            DataSet ds = postedFile.GetDataFromUploadFile(httpContext, fileName);

            StringBuilder deviceImportLog = new StringBuilder();
            StringBuilder deviceImportId = new StringBuilder();

            int importDeviceCount = 0;//      

            foreach (DataRow row in ds.Tables[fileName].Rows)
            {
                string memberApplyItemID = row[0].ToString().Trim();

                database = Database.New();
                var reportItem = new DeviceReportItem();
                try
                {
                    /*
                             IDatabase,  Linq  ,          DataContext,                           DataContext,    DataContext       。 Linq ,  DataContext   Entity     DataContext             ,          Attach       DataContext ,     ,   DataContext    Entity new   ,                 ,            ,          ,     ID
                     */
                    //           
                    reportItem.DeviceReport = database.DeviceReports.SingleOrDefault(dr => dr.ID == deviceReportID);
                    var item = database.MemberApplyItems.SingleOrDefault(mai => mai.ID == Convert.ToInt16(memberApplyItemID));// request.GetEntity<MemberApplyItem>(database.MemberApplyItems, memberApplyItemID);
                    if (item != null)
                        reportItem.MemberApplyItem = item;

                    reportItem.Save(database);

                    importDeviceCount++;
                }
                catch (Exception e)
                {
                    writer.WriteLine(string.Format("        ,     {0},     :{1}", memberApplyItemID, e.Message));
                }
                deviceImportId.AppendFormat("{0},", reportItem.ID);
            }

            deviceImportLog.AppendFormat("     {0} ,     Id :
{1}
", importDeviceCount, deviceImportId.ToString()); //projectImportLog.AppendFormat(" :
{0}
", expertMatchString.ToString());
writer.WriteLine(deviceImportLog.ToString()); httpContext.DeleteFile(postedFile.FileName); writer.Close(); return logName; } } }

좋은 웹페이지 즐겨찾기