一、导出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[][];
columnsArray[] = nameArray;
columnsArray[] = boxLabelArray;
columnsArray[] = renderArray;
columnsArray[] = widthArray; return columnsArray;
}
private StringBuilder getExcelXML(string[][] columnsArray, int columnsCount, XDocument storeXDocument, string ExcelTitle)
{
int worksheetHeight = ;//Convert.ToInt16(storeXDocument.Root.Elements().First().Value) * 20 + 20;
int worksheetWidth = ;//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 = ; i < columnsCount; i++)
{
columnXml.Append("<ss:Column ss:AutoFitWidth=\"1\" ss:Width=\"");
columnXml.Append(columnsArray[][i]);
columnXml.Append("\" />");
headerXml.Append("<ss:Cell ss:StyleID=\"headercell\">");
headerXml.Append("<ss:Data ss:Type=\"String\">");
headerXml.Append(columnsArray[][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 + );
headerDetailXml.Append("\" ss:ExpandedRowCount=\"");
headerDetailXml.Append(dataCount + );
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 = ; j < columnsCount; j++)
{
string data = "";
//carlsirce 修改
var element = record.Elements().FirstOrDefault(e => e.Name.LocalName == columnsArray[][j]) == null ? null : record.Elements().FirstOrDefault(e => e.Name.LocalName == columnsArray[][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 = ; i < ids.Length - ; 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 / ).ToString() + "." + (expertApplyItem.Quantity * expertApplyItem.ApplyDevice.UnitPrice % / ).ToString() + "万元";
dr["型号"] = expertApplyItem.GetModels(expertApplyItem, Database);
dr["学院"] = expertApplyItem.MemberApply.College.Name;
dr["配置 (或构成)"] = expertApplyItem.ApplyDevice.Configuration;
dr["申报人"] = expertApplyItem.ApplicantName;
dr["单价 (万元)"] = (expertApplyItem.ApplyDevice.UnitPrice / ).ToString() + "." + (expertApplyItem.ApplyDevice.UnitPrice % / ).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 == ) 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[];
worksheet.Name = "导出设备";
Microsoft.Office.Interop.Excel.Range range;
long totalCount = dt.Rows.Count;
long rowRead = ;
float percent = ;
for (int i = ; i < dt.Columns.Count; i++)
{
worksheet.Cells[, i + ] = dt.Columns[i].ColumnName;
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[, i + ];
range.Interior.ColorIndex = ;
range.Font.Bold = true;
}
for (int r = ; r < dt.Rows.Count; r++)
{
for (int i = ; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + , i + ] = dt.Rows[r][i].ToString();
}
rowRead++;
percent = ((float)( * 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[], 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[][].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 = ;//导入设备个数 foreach (DataRow row in ds.Tables[fileName].Rows)
{
string memberApplyItemID = row[].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;
}
}
}
.NET环境下导出Excel表格的两种方式和导入两种类型的Excel表格的更多相关文章
-
痞子衡嵌入式:在IAR开发环境下将关键函数重定向到RAM中执行的三种方法
大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家分享的是在IAR开发环境下将关键函数重定向到RAM中执行的三种方法. 嵌入式项目里应用程序代码正常是放在 Flash 中执行的,但有时候也需要将 ...
-
痞子衡嵌入式:在MDK开发环境下将关键函数重定向到RAM中执行的几种方法
大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家分享的是在MDK开发环境下将关键函数重定向到RAM中执行的几种方法. 这个关键函数重定向到 RAM 中执行系列文章,痞子衡已经写过 <IA ...
-
在 Windows 和 Linux(Gnome) 环境下 从命令界面打开网页的方式
1.在 Windows 中 通过命令 可以打开网页是很简单的: start http://www.baidu.com 或 start iexplorer http://www.baidu.com 第二 ...
-
React组件导入的两种方式(动态导入组件的实现)
一. react组件两种导入方式 React组件可以通过两种方式导入另一个组件 import(常用) import component from './component' require const ...
-
flask框架--设置配置文件的几种方式 与Flask两种配置路由的方式
设置配置文件的几种方式 ==========方式一:============ app.config['SESSION_COOKIE_NAME'] = 'session_lvning' #这种方式要把所 ...
-
Gradle环境下导出Swagger为PDF
更多精彩博文,欢迎访问我的个人博客 说明 我个人是一直使用Swagger作为接口文档的说明的.但是由于在一些情况下,接口文档说明需要以文件的形式交付出去,如果再重新写一份文档难免有些麻烦.于是在网上看 ...
-
Yii2 PHPExcel在linux环境下导出报500错误
断点调试后发现是因为这句报错 header('Content-Type : application/vnd.ms-excel');删除后正常输出下载
-
在Linux环境下,将Solr部署到tomcat7中,导入Mysql数据库数据, 定时更新索引
什么是solr solr是基于Lucene的全文搜索服务器,对Lucene进行了扩展优化. 准备工作 首先,去下载以下软件包: JDK8:jdk-8u60-linux-x64.tar.gz TOMCA ...
-
Linux16.04 LTS 环境下将cmake的项目转换成eclipse可导入可调试的工程项目
Linux作为一个开源系统,其中的一个优势就是有效的将各种源码编译得到的库集合在一起,为项目的使用创建了便捷.通常情况下,我们在开发自己的开源项目时,喜欢使用cmake调用各种三方库,如opencv ...
随机推荐
-
挂FORM时找不到对应的功能(function)
表单 功能都已经定义,但是在菜单中增加时候没有这个可选的项. 解决办法:由于是功能太多,LOV显示限制为30000,因此将功能名前加CUX,提升其排序即可.也可以修改LOV显示限制数量.
-
获取ItemsControl中当前item的binding数据
直接用 {Binding} 就可以了,如下: <ItemsControl ItemsSource="{Binding Path=ProcessItems}"> < ...
-
kettle
Kettle(中文名称叫水壶)是一款ETL工具,纯java编写,可以在Window.Linux.Unix上运行,绿色无需安装,数据抽取高效稳定.Kettle家族包括4个产品:Spoon.Pan.CHE ...
-
C/C++默认浮点型
代码: #include <iostream> #include <cstdio> using namespace std; void test(int a){ cout< ...
-
14 fragment 创建
静态展示 注意 静态的开始进入界面的生命周期和动态的不同 详情:14 fragment注意点 步骤一:创建一个类继承 Fragment 代码类型一: package com.fmy.demo1; im ...
-
location.origin兼容IE
if (window["context"] == undefined) { if (!window.location.origin) { window.location.origi ...
-
【转载】 如何看待 2019 年 CS PhD 现扎堆申请且大部分为 AI 方向?未来几年 AI 泡沫会破裂吗?
原贴地址: https://www.zhihu.com/question/316135639 作为一个 AI 方向的在读博士生,实在是过的蛮闹心,无意中逛知乎发现了这个帖子,发现很适合现在的自己,于是 ...
-
微信公众平台如何与Web App结合?
Web App简而言之就是为移动平台而优化的网页,它可以表现得和原生应用一样,并且克服了原生应用一些固有的缺点.一般而言Web App最大的入口是浏览器,但现在微信公众平台作为新兴的平台,结合其内置浏 ...
-
Angular组件之间通讯
组件之间会有下列3种关系: 1. 父子关系 2. 兄弟关系 3. 没有直接关系 通常采用下列方式处理(某些方式是框架特有)组件间的通讯,如下: 1父子组件之间的交互(@Input/@Output/模板 ...
-
Tomcat出现java.lang.Exception: Socket bind failed
今天测试系统,Tomcat(apache-tomcat-6.0.20windows版)突然出现异常,导致JSP页面无法运行.错误提示如下:2014-3-12 17:13:29 org.apache.c ...