上传之前,先定义好公共模板,让用户下载模板excle,然后填写数据,再上传,前台通过表单异步提交到一般处理程序
using System;
using System.Collections.Generic;using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
namespace TempCms.comment
{
/// <summary>
/// Excl_In 的摘要说明
/// </summary>
public class Excl_In : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
HttpPostedFile file = context.Request.Files["daoruFile"];
string saname = context.Request["saname"];
string resule = "";
string fileExtenSion;
fileExtenSion = Path.GetExtension(file.FileName);
if (fileExtenSion.ToLower() != ".xls" && fileExtenSion.ToLower() != ".xlsx")
{
resule="上传的文件格式不正确";
}
else
{
DataTable dt = xsldata(file, saname, fileExtenSion);//excle转换成datatable
resule = DataInSql(dt);
}
context.Response.Write(resule);
}
private string DataInSql(DataTable dt)
{
try
{
//dataGridView2.DataSource = ds.Tables[0];
int insertcount = 0;//记录插入成功条数
int updatecount = 0;//记录更新信息条数
string strcon = "server=(local);database=HXcms;uid=sa;pwd=sql@2008";
//string strcon = "server=192.168.0.190;database=HXcms;uid=sa;pwd=sql@2008";
SqlConnection conn = new SqlConnection(strcon);//链接数据库
conn.Open();
for (int i = 0; i < dt.Rows.Count; i++)
{
string cardNum = dt.Rows[i][0] == null ? "" : dt.Rows[i][0].ToString();//dt.Rows[i]["Name"].ToString(); "Name"即为Excel中Name列的表头
string uname = dt.Rows[i][1] == null ? "" : dt.Rows[i][1].ToString();
int age = dt.Rows[i][2] == null ? 0 : int.Parse(dt.Rows[i][2].ToString());
string sex = dt.Rows[i][3] == null ? "" : dt.Rows[i][3].ToString();
switch (sex)
{
case "男":
sex = "1";
break;
case "女":
sex = "2";
break;
default:
break;
}
string tel = dt.Rows[i][4] == null ? "" : dt.Rows[i][4].ToString(); ;
string address = dt.Rows[i][5] == null ? "" : dt.Rows[i][5].ToString();
string shenfenzheng = dt.Rows[i][6] == null ? "" : dt.Rows[i][6].ToString();
string pwd = dt.Rows[i][7] == null ? "" : dt.Rows[i][7].ToString();
decimal yu_e = dt.Rows[i][8] == null ? 0 : decimal.Parse(dt.Rows[i][8].ToString());
decimal zong_e_jia = dt.Rows[i][9] == null ? 0 : decimal.Parse(dt.Rows[i][9].ToString());
decimal zong_e_jian = dt.Rows[i][10] == null ? 0 : decimal.Parse(dt.Rows[i][10].ToString());
int jifen_zong = dt.Rows[i][11] == null ? 0 : int.Parse(dt.Rows[i][11].ToString());
int jifen = dt.Rows[i][12] == null ? 0 : int.Parse(dt.Rows[i][12].ToString());
string saname = "gzxxjs";
//if (Name != "" && Sex != "" && Age != 0 && Address != "")
//{
SqlCommand selectcmd = new SqlCommand("select count(*) from wxMemberCard where Wxmcstkh='" + cardNum + "' and Wxmcusername='" + "gzxxjs'", conn);
int count = Convert.ToInt32(selectcmd.ExecuteScalar());
if (count > 0)
{
updatecount++;
}
else
{
SqlCommand insertcmd = new SqlCommand("insert into wxMemberCard(Wxmcnum,Wxmcstate,Wxmcshzt,Wxmcstkh,Wxmcname,wxmage,Wxmgender,Wxmctel,Wxmidress,Wxmidentity,wxmcstkhpwd,Wxmchykye,Wxmchykczze,Wxmchykxfze,Wxmclszjf,Wxmcjifen,Wxmcusername) values('',0,2,'" + cardNum + "','" + uname + "'," + age + ",'" + sex + "','" + tel + "','" + address + "','" + shenfenzheng + "','" + pwd + "'," + yu_e + "," + zong_e_jia + "," + zong_e_jian + "," + jifen_zong + "," + jifen + ",'" + saname + "')", conn);
insertcmd.ExecuteNonQuery();
insertcount++;
}
//}
//else
//{
// errorcount++;
//}
}
return "成功上传:(" +insertcount + ")条数据!</br>重复数据:(" + updatecount + ")条";
}
catch (Exception ex)
{
return "操作失败";
}
}
/// <summary>
/// 讲excle转换成datatable
/// </summary>
/// <param name="file">excle文件</param>
/// <param name="saname">登录名</param>
/// <param name="fileExtenSion">扩展名</param>
/// <returns></returns>
private DataTable xsldata(HttpPostedFile file, string saname, string fileExtenSion)
{
try
{
string FileName = "App_Data/" + Path.GetFileName(file.FileName);
if (File.Exists(HttpRuntime.AppDomainAppPath + saname + "/" + file.FileName))
{
File.Delete(HttpRuntime.AppDomainAppPath + saname + "/" + file.FileName);
}
file.SaveAs(HttpRuntime.AppDomainAppPath + saname + "/" + file.FileName);
//HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES
string connstr2003 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + HttpRuntime.AppDomainAppPath + saname + "/" + file.FileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
string connstr2007 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + HttpRuntime.AppDomainAppPath + saname + "/" + file.FileName + ";Extended Properties=\"Excel 12.0;HDR=YES\"";
OleDbConnection conn;
if (fileExtenSion.ToLower() == ".xls")
{
conn = new OleDbConnection(connstr2003);
}
else
{
conn = new OleDbConnection(connstr2007);
}
conn.Open();
string sql = "select * from [Sheet1$]";
OleDbCommand cmd = new OleDbCommand(sql, conn);
DataTable dt = new DataTable();
OleDbDataReader sdr = cmd.ExecuteReader();
dt.Load(sdr);
sdr.Close();
conn.Close();
//删除服务器里上传的文件
if (File.Exists(HttpRuntime.AppDomainAppPath + saname + "/" + file.FileName))
{
File.Delete(HttpRuntime.AppDomainAppPath + saname + "/" + file.FileName);
}
return dt;
}
catch (Exception e)
{
return null;
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}