一、导出Excel表格的两种方式,其中两种方式指的是导出XML数据类型的Excel(即保存的时候可以只需要修改扩展名为.xls)和真正的Excel这两种。
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 &P of &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(); } } }
二、导入两种类型的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为:\n{1}\n", importDeviceCount, deviceImportId.ToString()); //projectImportLog.AppendFormat("项目成员匹配情况如下:\n{0}\n", expertMatchString.ToString()); writer.WriteLine(deviceImportLog.ToString()); httpContext.DeleteFile(postedFile.FileName); writer.Close(); return logName; } } }