求解asp.net mvc 中上传excel 如何导入到数据库中!!!

Sampson890727 2011-05-06 09:27:20
如何在mvc中实现excel的导入,并将导入的数据,先存到临时表,然后根据选择性的数据,插入到数据库。。。求各位MVC高手指教!!!最好附加个例子!!源码更好,借鉴研究一下! O(∩_∩)O谢谢各位喽!
...全文
1297 22 打赏 收藏 转发到动态 举报
写回复
用AI写文章
22 条回复
切换为时间正序
请发表友善的回复…
发表回复
坐看昀起 2013-01-10
  • 打赏
  • 举报
回复

//控制器
/// <summary>         /// 导入Excel方法         /// </summary>         /// <param name="fileSite"></param>         /// <returns></returns>         [HttpPost]         public ActionResult ImportSiteInfo(string fileSite)         {             if (string.IsNullOrEmpty(fileSite))                 return View();             ImportExcel importEx = new ImportExcel();             //获取Excel中的数据             DataTable dtSite = importEx.ExcelDataSource(fileSite, "Sheet1").Tables[0];             //添加到数据库             foreach (DataRow item in dtSite.Rows)             {                 Site s = new Site()                 {                     Name = item["Name"].ToString().Trim(),                     LocalID = int.Parse(item["LocalID"].ToString().Trim())                 };                 //判断当前站点是否存在                 if (!string.IsNullOrEmpty(SiteManageBusiness.GetSiteNameByName(s.Name)))                     continue;                 SiteManageBusiness.AddSiteInfo(s);             }             /*在跳转页面时传递一个标志位*/            return RedirectToAction("SiteInfoList", "SiteManage", new { import = 1 });         }                   /// <summary>         /// 站点信息一览         /// </summary>         /// <param name="page">当前索引</param>         /// <param name="pageSize">当前页面显示条数</param>         /// <returns></returns>         public ActionResult SiteInfoList(int page = 1, int pageSize = 15)         {             //判断是否为初始化页面             if (Request.QueryString["flagSite"] != null)             {                 Session["site"] = null;             }             /*接一下数值*/            if (Request.QueryString["import"] != null)             {                 ViewBag.flag = 1;             }             SiteModel siteInfo = new SiteModel()             {                 //区域ID值(默认值)                  LocalID = -1             };             //查询条件不为空             if (Session["site"] != null)             {                 siteInfo = Session["site"] as SiteModel;                 //区域名称                 ViewBag.LocalName = siteInfo.LocalName;                 //站点名称                 ViewBag.SiteName = siteInfo.Name;             }             PagerIndexModel model = new PagerIndexModel             {                 CurrentPageIndex = page,                 PageSize = pageSize,                 //确定记录总数(才能计算出PageCount页数)                                 TotalRecordCount = SiteManageBusiness.GetSiteInfoByEntity(siteInfo).ToList<Site>().Count,             };             // 获取当前页的信息                         model.SiteInfomationList = SiteManageBusiness.GetSiteInfoByEntity(siteInfo).OrderBy(p => p.ID).Skip((model.CurrentPageIndex - 1) * model.PageSize).Take(model.PageSize);             return View(model);         } 




//导入Excel方法
     /// <summary>
        /// 获取Excel数据方法
        /// </summary>
        /// <param name="filepath">文件路径</param>
        /// <param name="sheetname">sheet名称</param>
        /// <returns></returns>
        public DataSet ExcelDataSource(string filepath, string sheetname)
        {
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";
            OleDbConnection conn = new OleDbConnection(strConn);
            OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + sheetname + "$]", strConn);
            DataSet ds = new DataSet();
            oada.Fill(ds);
            return ds;
        }

dreamerrant 2012-09-30
  • 打赏
  • 举报
回复
很有用的功能,正在找相关代码,学习一下。
Sampson890727 2011-10-26
  • 打赏
  • 举报
回复
[Quote=引用 18 楼 cc_lq 的回复:]

能不能加好友,交流一下~~
[/Quote]可以,我的Q是2511207640
Sampson890727 2011-10-26
  • 打赏
  • 举报
回复
[Quote=引用 18 楼 cc_lq 的回复:]

能不能加好友,交流一下~~
[/Quote]
可以,我的Q是2511207640
小李哥哥 2011-10-20
  • 打赏
  • 举报
回复
能不能加好友,交流一下~~
Sampson890727 2011-10-13
  • 打赏
  • 举报
回复
DataTable dt = GeneralRequestDetail.GetGeneralInfoToExcel(new Guid(calendarId),expenseType,startDate,endDate,employeeNo,employeeName,isPass);

//if (dt.Rows.Count > 0)

//{

// if (excelInfo.DoExport(dt))

// {



// return RedirectToAction("InvoiceList", new { calendarId = calendarId });

// }

// return View();

//}

// return RedirectToAction("InvoiceList", new { calendarId = calendarId });

StringBuilder result = new StringBuilder();

//result.Append("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=UTF-8\"/>"); // the key!!!

//result.Append("<table>");



////prepare header...

if (dt.Rows.Count > 0)

{

result.Append("<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>");

result.Append("<head><title></title><meta http-equiv='Content-Type' content=\"text/html; charset=UTF-8\">");

//注意:[if gte mso 9]到[endif]之间的代码,用于显示Excel的网格线,若不想显示Excel的网格线,可以去掉此代码

result.Append("<!--[if gte mso 9]>");

result.Append("<xml>");

result.Append(" <x:ExcelWorkbook>");

result.Append(" <x:ExcelWorksheets>");

result.Append(" <x:ExcelWorksheet>");

result.Append(" <x:Name>Sheet1</x:Name>");

result.Append(" <x:WorksheetOptions>");

result.Append(" <x:Print>");

result.Append(" <x:ValidPrinterInfo />");

result.Append(" </x:Print>");

result.Append(" </x:WorksheetOptions>");

result.Append(" </x:ExcelWorksheet>");

result.Append(" </x:ExcelWorksheets>");

result.Append("</x:ExcelWorkbook>");

result.Append("</xml>");

result.Append("<![endif]-->");

result.Append("</head><body><table style='border-collapse:collapse;table-layout:fixed;'><tr>");



//result.Append("<tr>");

result.Append("<td><b>" + "公司编号" + "</b></td>");

result.Append("<td><b>" + "公司名称" + "</b></td>");

result.Append("<td><b>" + "员工编号" + "</b></td>");

result.Append("<td><b>" + "员工姓名" + "</b></td>");

result.Append("<td><b>" + "表单编号" + "</b></td>");

result.Append("<td><b>" + "报销编号" + "</b></td>");

result.Append("<td><b>" + "发票编号" + "</b></td>");

result.Append("<td><b>" + "费用类别" + "</b></td>");

result.Append("<td><b>" + "是否有效" + "</b></td>");

result.Append("<td><b>" + "备注" + "</b></td>");

result.Append("<td><b>" + "真伪" + "</b></td>");

result.Append("<td><b>" + "名称" + "</b></td>");

result.Append("<td><b>" + "日期" + "</b></td>");

result.Append("<td><b>" + "金额" + "</b></td>");

result.Append("</tr>\n");

for (int j = 0; j < dt.Rows.Count; j++)

{

result.Append("<tr>");

for (int k = 0; k < dt.Columns.Count; k++)

{

object obj = dt.Rows[j][k];

//result.Append("<td><b>" + obj.ToString() + "</b></td>");

result.AppendFormat("<td style='vnd.ms-excel.numberformat:@'>{0}</td>", obj);

}

result.Append("</tr>\n");

}



Response.Clear();

Response.Buffer = true;

Response.ContentEncoding = Encoding.UTF8;

Response.Charset = "utf-8";

Response.ContentType = "application/ms-excel";

Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("InvoiceInfo", Encoding.UTF8) + ".xls");

Response.Write(result.ToString());

Response.Flush();

Response.End();

}

return RedirectToAction("InvoiceList", new { calendarId = calendarId, expenseType = expenseType, startDate = startDate, endDate = endDate, employeeNo = employeeNo, employeeName = employeeName, isPass = isPass });
小李哥哥 2011-09-21
  • 打赏
  • 举报
回复
对啊,楼主把代码帖出来让大家看看,我也不会,急求啊~~~~
peter_xizi 2011-08-02
  • 打赏
  • 举报
回复
楼主,把程序帖出来
Sampson890727 2011-05-11
  • 打赏
  • 举报
回复
呵呵,自己已经专研出来了,O(∩_∩)O哈哈~
cjh200102 2011-05-11
  • 打赏
  • 举报
回复
啥也不说了。
项一下。
楼上很全面了。
Lisliefor 2011-05-11
  • 打赏
  • 举报
回复
ExcelExportHandler类的定义:

public class ExcelExportHandler
{
public static void ExportFile(string content, string contentType, string charSet, string encodingName, string outPutFileName)
{
byte[] htmlBy = System.Text.Encoding.GetEncoding("GB2312").GetBytes(content);
MemoryStream stream = new MemoryStream(htmlBy);
ExportFile(stream, contentType, charSet, encodingName, outPutFileName);
}

public static void ExportFile(MemoryStream stream, string contentType, string charSet, string encodingName, string outPutFileName)
{


HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = contentType;
HttpContext.Current.Response.Charset = charSet;
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(encodingName);
String userAgent;
userAgent = HttpContext.Current.Request.UserAgent;
if (userAgent != null && userAgent.ToUpper().IndexOf("MSIE") > -1)
{
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(outPutFileName, System.Text.Encoding.UTF8).Replace("+", "%20"));
// The browser is Microsoft Internet Explorer Version 6.0.
}
else if (userAgent != null && userAgent.ToUpper().IndexOf("MOZILLA") > -1)
{
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlDecode(outPutFileName, System.Text.Encoding.UTF8).Replace("+", "%20"));

}

HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.GetEncoding(encodingName);
stream.WriteTo(HttpContext.Current.Response.OutputStream);
//HttpContext.Current.Response.End();
}
}
Lisliefor 2011-05-11
  • 打赏
  • 举报
回复
读取excel模板,导出excel的例子:


public ActionResult ExportQualifiedExaminees(int serviceid, int funcid, string condition)
{

RegistrationBLL bll = new RegistrationBLL();
IList<QualifiedExamineeEn> list = bll.GetQualifiedExaminees(serviceid, condition);
if (list == null || list.Count == 0)
{
return Alert("没有准考证信息", "~/Views/ExamService/SaveSuccess.aspx", new { controller = "Registration", action = "GetExamineeByPage", serviceid = serviceid, funcid = funcid });
}

using (MemoryStream m = bll.ExportQualifiedExaminees(Server.MapPath("~/Resources/考生签到表导出模版.xls"), list1[0].fServiceName, list, Server.MapPath("~/Common/Images/toeic_log.PNG")))
{
ExcelExportHandler.ExportFile(m, "application/ms-excel", "UTF-8", "GB2312", "考生签到表.xls");
}

return new EmptyResult();
}
Lisliefor 2011-05-11
  • 打赏
  • 举报
回复
导出CSV文件的例子:

public ActionResult ExportQualifiedExaminee(int serviceid, int funcid, string condition)
{

RegistrationBLL bll = new RegistrationBLL();
IList<QualifiedExamineeEn> list = bll.GetQualifiedExaminees(serviceid, condition);

StringBuilder sb = new StringBuilder();
sb.Append("序号,姓,名,性别,出生日期,登录名,工号,部门,准考证号,证件类型,证件号码,学历,专业,考场地址,手机,Email,企业名称,国籍\r\n");
if (list != null && list.Count > 0)
{
int i = 0;
foreach (var item in list)
{
i++;
sb.Append(i.ToString());
sb.Append(",\t" + item.FirstName.Replace(",", ","));
sb.Append(",\t" + item.LastName.Replace(",", ","));
if (item.IDNumber != null && item.IDNumber.Trim().Length > 0)
{
sb.Append("," + (item.Gender == true ? "男" : "女"));
sb.Append(",\t" + item.Birthday);
}
else
{
sb.Append("," + "");
sb.Append("," + "");
}
sb.Append(",\t" + item.LogonName.Replace(",", ","));
sb.Append(",\t" + item.EmployeeNum.Replace(",", ","));
sb.Append(",\t" + item.Department.Replace(",", ","));
sb.Append(",\t" + item.AdmissionFormId.Replace(",", ",")); //增加\t表示导出csv时,为文本数据
sb.Append(",\t" + item.IDTypeName);
sb.Append(",\t" + item.IDNumber.Replace(",", ","));
sb.Append(",\t" + item.EducationName.Replace(",", ","));
sb.Append(",\t" + item.EducationMajorName.Replace(",", ","));
sb.Append(",\t" + item.LocationAddress.Replace(",", ","));
sb.Append(",\t" + item.Contact.Replace(",", ","));
sb.Append(",\t" + item.Email.Replace(",", ","));
sb.Append(",\t" + item.CompanyName.Replace(",", ","));
sb.Append(",\t" + item.National.Replace(",", ","));
sb.Append("\r\n");
}

}
else
{
return Alert("没有准考证信息", "~/Views/ExamService/SaveSuccess.aspx", new { controller = "Registration", action = "GetExamineeByPage", serviceid = serviceid, funcid = funcid });
}
ExcelExportHandler.ExportFile(sb.ToString(), "application/ms-excel", "UTF-8", "GB2312", "合格考生.csv");

return new EmptyResult();
}
Sampson890727 2011-05-07
  • 打赏
  • 举报
回复
求列子额!!!!!!!!!!!!
Lisliefor 2011-05-06
  • 打赏
  • 举报
回复
做法一样的啊,在controller中,读取页面上选择的excel的路径,然后用上面的方法读取excel的数据,插入数据库,接着,要不查询,要不给个提示,就完事了。
Sampson890727 2011-05-06
  • 打赏
  • 举报
回复
不要沉额。各位高手速来指教额, 给力啊!!!!
回头是岸 2011-05-06
  • 打赏
  • 举报
回复
OleDb不就可以啦
Sampson890727 2011-05-06
  • 打赏
  • 举报
回复
MVC需要在controller中处理。。。该怎么做,急求!!
Sampson890727 2011-05-06
  • 打赏
  • 举报
回复
给一个详细点的代码,让偶瞅瞅[Quote=引用 3 楼 claymore1114 的回复:]

跟 mvc 没关系,webform怎么用 还是怎么用,网上搜一下 。
[/Quote]
claymore1114 2011-05-06
  • 打赏
  • 举报
回复
跟 mvc 没关系,webform怎么用 还是怎么用,网上搜一下 。
加载更多回复(2)

62,064

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧